在 Express 中接收 Jquery POST 数据

Run*_*olk 4 javascript jquery post node.js express

编辑请参阅下面接受的答案以获取修复。我还必须contentType: 'appliction/json',从我的 POST 请求中删除该行。

我正在尝试向 Node.js/Express 发送一个字符串,但它req.body是未定义的服务器端。

客户端jQuery:

$.post({
        traditional: true,
        url: '/matches',
        contentType: 'appliction/json',
        data: viewedProfiles,
        dataType: 'json',
        success: function(response){
Run Code Online (Sandbox Code Playgroud)

表达:

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.post('/matches', isLoggedIn, function(req, res){
  console.log(req.body) // this is undefined
  var loadedProfiles = []
  loadedProfiles.push(req.body.viewedProfiles)
  console.log('loadedProfiles')
  console.log(loadedProfiles)
Run Code Online (Sandbox Code Playgroud)

我试过了:

  • 未指定“数据类型”
  • 环境 data: JSON.stringify(viewProfiles)
  • 在客户端将字符串拆分为数组,然后让 jQuery 对其进行字符串化
  • 寻找 req.params 而不是 req.body (紧抓稻草)

我可以在开发工具中看到 XHR 请求,它包含我期望的字符串。

将数据发送到 Express 时我错过了什么非常明显的事情?

谢谢。

Ari*_*han 6

您的服务器端代码看起来不错,但您需要使用$.ajax()而不是 $.post()函数,因为$.post()函数将数据发送到 url(使用 url 编码)。所以你的 JQuery 代码是

$.ajax({
        url: '/matches',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({"viewedProfiles": viewedProfiles}),
        success: function(response){
Run Code Online (Sandbox Code Playgroud)

我希望这能帮到您


Kar*_*tal 5

我已经配置了完全相同的设置。下面的代码有效:

var profiles = { 'data' : 'hello' };

$.post({
        traditional: true,
        url: '/matches',
        contentType: 'application/json',
        data: JSON.stringify( profiles ),
        dataType: 'json',
        success: function(response){ console.log( response ); }
} );
Run Code Online (Sandbox Code Playgroud)

我的 nodejs 引擎:

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.post( '/matches' , function(req, res){
  console.log(req.body) // this outputs: { data: 'hello' }
} );
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你的 contentType 有一个拼写错误,'applic A tion/json'