1 javascript ajax json node.js express
问题:解析JSON的对象是什么?
我已成功向服务器发送JSON字符串,但我无法访问该对象.
客户端脚本,发送JSON:
var loginCredentials= {
"username":creds.username,
"password":creds.password };
request = $.ajax({
url: "http://127.0.0.1:8080/login",
type: "POST",
crossDomain: true,
data: JSON.stringify(loginCredentials),
dataType: "json"
});
Run Code Online (Sandbox Code Playgroud)
登录监听器,等待并假设解析JSON:
function listen(){
app.use(express.bodyParser());
app.post('/login', function(req, res) {
var util = require('util');
console.log(util.inspect(req.body, false, null));
console.log(req.body.username);
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
}
Run Code Online (Sandbox Code Playgroud)
哪些日志:
Server running at http://127.0.0.1:8080/
{ '{"username":"username1","password":"badpassword"}': '' }
undefined
Run Code Online (Sandbox Code Playgroud)
所以看起来我的JSON被解析正确,但我试图通过req.body.username访问它并且它不存储在那里.
bodyParser不知道您正在发送JSON.它假定主体是标准的www-form-urlencoded,因此将其全部解析为单个密钥.
相反,请根据您的请求发送正确的内容类型:
request = $.ajax({
url: "http://127.0.0.1:8080/login",
type: "POST",
crossDomain: true,
data: JSON.stringify(loginCredentials),
contentType : 'application/json',
dataType: "json" // response type
});
Run Code Online (Sandbox Code Playgroud)
但是,如不使用带有Express.js的bodyParser中所述,您可能只使用express.json()中间件.
| 归档时间: |
|
| 查看次数: |
2778 次 |
| 最近记录: |