[英]Ajax Post with express js get req parameter error
我正在使用ajax从javascript前端发布数据来表达js有后端服务器。 我如何在 express js api 方法 req params 中获取发布的数据。 当我尝试解析下面的请求数据时遇到问题是我的代码。请帮我解决这个问题
$.ajax({
url: "http://localhost:8080/api/save_user/",
type: "POST",
crossDomain: true,
data: { name: 'Justin', number: '662***' },
dataType: "json",
contentType: "application/json",
success: function (response) {
var resp = JSON.parse(response)
},
error: function (xhr, status) {
alert("error");
}
});
Express Js 服务器端
const express = require('express');
const path = require('path')
const os = require('os');
const app = express();
var bodyParser = require('body-parser')
app.use(bodyParser.json())
//deploy the smart contract
app.post('/api/save_user', (req, res) => {
console.log((JSON.parse(req.body)));
res.send({})
})
错误日志
SyntaxError: Unexpected token n in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (/node_modules/body-parser/lib/types/json.js:158:10)
at parse (/node_modules/body-parser/lib/types/json.js:83:15)
at /node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/raw-body/index.js:224:16)
问题是 jquery 期望你传递一个带有 json 的字符串。 试试这样:
$.ajax({ url: "http://localhost:8080/api/save_user/", type: "POST", crossDomain: true, data: JSON.stringify({ name: 'Justin', number: '662***' }), dataType: "json", contentType: "application/json", success: function (response) { var resp = JSON.parse(response) }, error: function (xhr, status) { } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.