簡體   English   中英

在Node.JS中讀取AJAX post變量(使用Express)

[英]Reading AJAX post variables in Node.JS (with Express)

我正在嘗試獲取我在節點應用程序中發送ajax帖子的值。 這篇文章為指導,到目前為止我有這個:

在節點中:

 var express = require('express');
 var app = express();

 var db = require('./db');

 app.get('/sender', function(req, res) {
    res.sendfile('public/send.html');
 });

 app.post('/send_save', function(req, res) {
  console.log(req.body.id)
  console.log(req.body.title);
  console.log(req.body.content);
  res.contentType('json');
  res.send({ some: JSON.stringify({response:'json'}) });
});

app.listen(3000);

在AJAX方面:

$('#submit').click(function() {
            alert('clicked')
            console.log($('#guid').val())
            console.log($('#page_title').val())
            console.log($('#page-content').val())
            $.ajax({
                url: "/send_save",
                type: "POST",
                dataType: "json",
                data: {
                    id: $('#guid').val(),
                    title: $('#page_title').val(),
                    content: $('#page-content').val()
                },
                contentType: "application/json",
                cache: false,
                timeout: 5000,
                complete: function() {
                  //called when complete
                  console.log('process complete');
                },

                success: function(data) {
                  console.log(data);
                  console.log('process sucess');
               },

                error: function() {
                  console.log('process error');
                },
              });
        })

這個問題是我不能req.body.id(以及任何其他值,如標題或內容),我在節點中收到此錯誤:

 TypeError: Cannot read property 'id' of undefined

如果我評論這些呼叫,ajax是成功的。 我搞不清楚了。 我忘記了什么嗎?

你在那里的req對象沒有body屬性。 看看http://expressjs.com/api.html#req.body

此屬性是包含已解析請求正文的對象。 此功能由bodyParser()中間件提供,但其他正文解析中間件也可遵循此約定。 使用bodyParser()時,此屬性默認為{}。

因此,您需要將bodyParser中間件添加到您的快速webapp中,如下所示:

var app = express();
app.use(express.bodyParser());

通過包含thejh建議的bodyParser中間件確實解決了這個問題。

只需確保訪問該答案中提供的URL以訪問Express更新的規范: http//expressjs.com/api.html#req.body

該文檔提供了此示例(Express 4.x):

var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); 

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data

app.post('/', function (req, res) {
  console.log(req.body);
  res.json(req.body);
})

為此,需要單獨安裝body-parser模塊:

https://www.npmjs.com/package/body-parser

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM