当尝试在 post 端点上传递 json 数据时,我发现主体部分未定义,这是在我将 api 划分到不同的文件后发生的,之后我收到 ER_BAD_NULL_ERROR: Column 'User' can not be null 错误,但无法找到错误的根源
"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.18.3",
"mysql": "^2.18.1",
"nodemailer": "^6.9.12",
"nodemon": "^3.1.0",
"routes": "^2.1.0"
}
//Index.js
const express = require('express');
const userRoutes = require("./Routes/userRoutes");
const app = express();
// Middleware for parsing JSON body
app.use(express.json());
app.use(express.urlencoded({extended: true}));
// Use routes
app.use('/api/users', userRoutes);
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
//userRoutes.js
const express = require('express');
const nodemailer = require('nodemailer');
const mysql = require('mysql');
const router = express.Router();
//var bodyParser = require('body-parser');
//router.use(express.json());
//router.use(express.urlencoded({extended: false}));
var error = 0;
// Define user routes
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'contacts'
});
// Middleware for sending emails
const transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: '',
pass: ''
}
});
// Functions here
function ValidarInput(name, password, Google_Login, Apple_Login, Apple_Id, Saldo, ValorDevido, IS_Allowed ) {
if (!name || !password || Google_Login == null || Apple_Login == null || !Apple_Id || Saldo == null || ValorDevido == null || IS_Allowed == null) {
console.log("Failed to create user");
}
}
//Functions here
// Connect to MySQL
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL: ' + err.stack);
return;
}
console.log('Connected to MySQL as id ' + connection.threadId);
});
// GET all users
router.get('/', (req, res) => {
connection.query('SELECT * FROM users', (error, results, fields) => {
if (error) {
console.error('Error retrieving users: ' + error);
res.status(500).json({ message: 'Internal server error' });
return;
}
res.json(results);
});
});
router.get('/:id', (req, res) => {
connection.query(`SELECT * FROM users WHERE id = ${req.params.id}` , (error, results, fields) => {
if (error) {
console.error('Error retrieving users: ' + error);
res.status(500).json({ message: 'Internal server error' });
return;
}
res.json(results);
});
});
router.post('/', (req, res) => {
const { name, password, Google_Login, Apple_Login, Apple_Id, Saldo, ValorDevido, IS_Allowed } = req.body;
ValidarInput(name, password, Google_Login, Apple_Login, Apple_Id, Saldo, ValorDevido, IS_Allowed);
if (error != 0) {
return res.status(400).json({ message: 'All fields are required' });
}else{
connection.query(`INSERT INTO users (User, Password, Google_Login, Apple_Login, Apple_Id, Saldo, ValorDevido, IS_Allowed) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[name, password, Google_Login, Apple_Login, Apple_Id, Saldo, ValorDevido, IS_Allowed], (error, results, fields) => {
if (error) {
console.error('Error creating user: ' + error);
res.status(500).json({ message: 'Internal server error' });
return;
}
res.status(201).json({ id: results.insertId, name, password, Google_Login, Apple_Login, Apple_Id, Saldo, ValorDevido, IS_Allowed });
});
}
});
// PATCH/UPDATE user by ID
router.patch('/:id', (req, res) => {
const userId = req.params.id;
const { name, password, Google_Login, Apple_Login, Apple_Id, Saldo, ValorDevido, IS_Allowed } = req.body;
let updateQuery = 'UPDATE users SET ';
let updateFields = [];
let updateValues = [];
if (!name) {
updateFields.push('User=?');
updateValues.push(name);
}
if (Google_Login !== undefined) {
updateFields.push('Google_Login=?');
updateValues.push(Google_Login);
}
if (Apple_Login !== undefined) {
updateFields.push('Apple_Login=?');
updateValues.push(Apple_Login);
}
if (Apple_Id) {
updateFields.push('Apple_Id=?');
updateValues.push(Apple_Id);
}
if (Saldo !== undefined) {
updateFields.push('Saldo=?');
updateValues.push(Saldo);
}
if (ValorDevido !== undefined) {
updateFields.push('ValorDevido=?');
updateValues.push(ValorDevido);
}
if (IS_Allowed !== undefined) {
updateFields.push('IS_Allowed=?');
updateValues.push(IS_Allowed);
}
if (updateFields.length === 0) {
return res.status(400).json({ message: 'No fields to update' });
}
updateQuery += updateFields.join(', ') + ' WHERE id=?';
updateValues.push(userId);
connection.query(updateQuery, updateValues, (error, results, fields) => {
if (error) {
console.error('Error updating user: ' + error);
res.status(500).json({ message: 'Internal server error' });
return;
}
res.json({ message: 'User updated successfully' });
});
});
router.patch('/:id/passwordreset', (req, res) => {
const userId = req.params.id;
const { password } = req.body;
let updateQuery = 'UPDATE users SET ';
let updateFields = [];
let updateValues = [];
if (password !== undefined) {
updateFields.push('Password=?');
updateValues.push(password);
}
if (updateFields.length === 0) {
return res.status(400).json({ message: 'No fields to update' });
}
updateQuery += updateFields.join(', ') + ' WHERE id=?';
updateValues.push(userId);
connection.query(updateQuery, updateValues, (error, results, fields) => {
if (error) {
console.error('Error updating user: ' + error);
res.status(500).json({ message: 'Internal server error' });
return;
}
res.json({ message: 'User updated successfully' });
});
});
// DELETE user by ID
router.delete('/:id', (req, res) => {
const userId = req.params.id;
connection.query('DELETE FROM users WHERE id = ?', userId, (error, results, fields) => {
if (error) {
console.error('Error deleting user: ' + error);
res.status(500).json({ message: 'Internal server error' });
return;
}
if (results.affectedRows === 0) {
return res.status(404).json({ message: 'User not found' });
}
res.json({ message: 'User deleted successfully' });
});
});
router.post('/send-email', (req, res) => {
const { to, subject, text } = req.body;
// Setup email data
const mailOptions = {
from: '[email protected]',
to: to,
subject: subject,
text: text
};
// Send email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error sending email:', error);
res.status(500).send('Error sending email');
} else {
console.log('Email sent:', info.response);
res.status(200).send('Email sent successfully');
}
});
});
// Export router
module.exports = router;
本来是要插入mysql数据库,但是无法传递数据
您似乎遇到了几个问题:
让我们一一解决这些问题:
部分身体问题: 当您在 Express 中处理 JSON 数据时,您应该确保在定义路由之前使用express.json() 中间件。在你的userRoutes.js中,你已经导入了express,所以你不需要再次导入它。
以下是更新 userRoutes.js 的方法:
const express = require('express');
const router = express.Router();
router.use(express.json()); // Adding this line to parse JSON requests
// Rest of your code goes here
module.exports = router;
ER_BAD_NULL_ERROR: 该错误表明“用户”列不能为空。这表明您尝试插入数据库的名称字段可能为空。您正在从 req.body 检索名称,因此您应该确保您的 POST 请求包含“名称”字段。
检查您的 POST 请求,确保您以正确的格式发送数据。如果“名称”是必填字段,请确保它在请求正文中正确发送。
此外,在 ValidarInput 函数中,您没有处理所有字段都正确存在的情况。您正在检查 if (error != 0) 这可能不是最好的方法。如果缺少任何字段,您应该从函数返回,而不是将错误设置为非零值。
以下是更新 ValidarInput 函数的方法:
function ValidarInput(name, password, Google_Login, Apple_Login, Apple_Id, Saldo, ValorDevido, IS_Allowed) {
if (!name || !password || Google_Login == null || Apple_Login == null || !Apple_Id || Saldo == null || ValorDevido == null || IS_Allowed == null) {
console.log("Failed to create user");
return false;
}
return true;
}
然后在您的 POST 路线中:
router.post('/', (req, res) => {
const { name, password, Google_Login, Apple_Login, Apple_Id, Saldo, ValorDevido, IS_Allowed } = req.body;
if (!ValidarInput(name, password, Google_Login, Apple_Login, Apple_Id, Saldo, ValorDevido, IS_Allowed)) {
return res.status(400).json({ message: 'All fields are required' });
}
// Rest of your code for inserting into the database
});
这些更改应该可以帮助您解决这两个问题。确保您在 POST 请求正文中发送正确的数据,并且 JSON 解析中间件已正确设置。