This is my first time building an express server in nodeJS, i don't know much of what im doing but i managed to make POSTs and GETs using routes and controllers... I don't know why req.body is showing {} on terminal, obviously im not receiving any data from the AJAX, but why? please help.
这是我第一次在NodeJS中构建Express服务器,我不知道我在做什么,但我设法使用路线和控制器发布和获取……我不知道为什么req.body在终端上显示{},显然我没有收到来自AJAX的任何数据,但为什么呢?请帮帮忙。
server.js
Server.js
const express = require('express');
const morgan = require('morgan');
const path = require("path");
const mysql = require('mysql');
const myConnection = require('express-myconnection');
const app = express();
const bodyParser = require('body-parser');
// Manejar solicitudes JSON
app.use(express.json());
// Configuración de acceso a la base de datos
const hostDB = "localhost";
const userDB = "root";
const passwordDB = "";
const portDB = 3306;
const databaseDB = 'motionpose';
// Importación de rutas
const usuarioRuta = require('./routes/usuarios');
const registroRuta = require('./routes/registroRuta');
// Configuración
app.set('port', process.env.PORT || 5555);
// Middlewares
app.use(morgan('dev'));
app.use(myConnection(mysql, {
host: hostDB,
user: userDB,
password: passwordDB,
port: portDB,
database: databaseDB
}, 'single'));
// Rutas
app.use('/login', usuarioRuta);
app.use('/registro', registroRuta);
// Archivos estáticos
app.use(express.static('public'));
// API
app.get('/', (req, res)=>{
res.sendFile(path.join(__dirname, 'view', 'index.html'))
});
app.listen(app.get('port'), ()=>{
console.log('Server corriendo en puerto: ' + app.get('port'));
});
usuarios.js
Usuarios.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser'); // Importa body-parser
const usuariosController = require('../controllers/usuariosController');
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
router.get('/', usuariosController.view);
router.post('/', usuariosController.post);
module.exports = router;
login.js
Login.js
$(document).ready(function(){
$("#continuarBoton").on("click", function(){
var formData = new FormData();
formData.append("correo", $("#correo").val());
formData.append("contrasena", $("#contrasena").val());
$.ajax({
url: '/login', // Reemplaza con la ruta correcta hacia tu función getUsuarios
method: 'POST',
dataType: 'json',
data: {
correo: "test1",
contrasena: "test2"
},
processData: false,
contentType: false,
success: function(data) {
console.log(data);
if(data.Exito){
console.log("Solicitud POST exitosa");
}else{
console.error("Solicitud POST DENEGADA");
}
},
error: function(error) {
console.error(error);
}
});
});
});
usuariosController.js
UsuariosController.js
const controller = {};
const path = require('path');
let usuariosLista = [];
let Exito;
controller.view = (req, res)=>{
res.sendFile(path.join(__dirname, '..', 'view', 'login.html'));
Exito = true;
};
controller.post = (req, res) => {
console.log("This is working");
console.log(req.body);
res.json({Exito: Exito});
}
module.exports = controller;
Terminal output:
终端输出:
This is working
{}
POST /login 200 3.802 ms - 14
Im expecting to console.log the data from AJAX.
Im receiving {} when printing req.body or undefined when I try to access an specific value, for example req.body.correo.
我期待console.log从AJAX的数据。我在打印req.body时接收到{},或者当我试图访问特定值时未定义,例如req. body. correo。
I already installed body-parser.
我已经安装了身体解析器。
更多回答
Consider not using jQuery; it did a great job a couple of decades ago when native browser APIs weren't very good, but times have changed.
考虑不使用jQuery;几十年前,当本机浏览器API不是很好时,它做得很好,但时代已经改变了。
You are right, but i already know how to use jquery and learning pure javascript makes me very lazy, but I will do it one day!
你是对的,但我已经知道如何使用jQuery,学习纯Java让我很懒,但总有一天我会这么做的!
优秀答案推荐
You said:
你说过:
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
So req.body
will be populated if you get a request where the data is encoded as either JSON or with URL Form Encoding and the request has a Content-Type
header that matches.
因此,如果您收到一个请求,其中数据被编码为JSON或URL表单编码,并且请求具有匹配的Content-Type头,则req.body将被填充。
Then you said:
然后你说:
data: {
correo: "test1",
contrasena: "test2"
},
You are passing an object to jQuery.
您正在将一个对象传递给jQuery。
Under normal circumstances it would encoded it as URL Form Encoded data and set the correct content-type.
在正常情况下,它会将其编码为URL形式的编码数据,并设置正确的内容类型。
However you also said:
但你也说:
processData: false,
… which tells jQuery not to process the value passed to data
so it hits the underlying XMLHttpRequest
object and is converted to the string [object Object]
(which is useless).
…它告诉jQuery不要处理传递给数据的值,这样它就会命中底层的XMLHttpRequest对象,并被转换为字符串[对象对象](这是无用的)。
You also said:
你还说过:
contentType: false,
… which tells jQuery not to set the content-type and let XMLHttpRequest
figure it out (which it will set to text/plain
).
…这告诉jQuery不要设置内容类型,让XMLHttpRequest来确定(它将设置为Text/Plain)。
Remove those two parameters.
删除这两个参数。
If you wanted to send JSON then you'd need to:
如果要发送JSON,则需要:
- Pass JSON to
data
- Set the content-type explicitly
data: JSON.stringify({
correo: "test1",
contrasena: "test2"
}),
contentType: 'application/json',
You still shouldn't set processData: false,
as jQuery doesn't do processing of strings in the first place.
您仍然不应该设置cessData:FALSE,因为jQuery从一开始就不处理字符串。
Aside
搁置一边
I already installed body-parser.
Don't do that.
别干那事。
Express has a dependency on body-parser and exposes it though the express object. Let it manage which version of body-parser you use instead of doing it manually.
EXPRESS依赖于正文解析器并通过EXPRESS对象公开它。让它管理您使用哪个版本的正文解析器,而不是手动执行。
Use express.json
and express.urlencoded
instead.
请改用exts.json和exts.urlencode。
更多回答
Friend, you are a lifesaver, you were exactly right about the ajax query, in fact I had copied that ajax from another older project, because I had forgotten about the structure and it was just those lines bothering me, thank you very much.
朋友,你是救世主,你关于AJAX查询的描述是完全正确的,事实上,我从另一个更老的项目中复制了那个AJAX,因为我忘记了结构,只是那些行困扰着我,非常感谢。
我是一名优秀的程序员,十分优秀!