【问题标题】:Access AJAX POST data with Node.js/Express使用 Node.js/Express 访问 AJAX POST 数据
【发布时间】:2017-02-19 01:26:26
【问题描述】:

我正在构建一个使用 Node.js/Express 作为后端的 Web 应用程序。

在我的前端,我通过 Javascript 向服务器发送一个 AJAX 请求,如下所示:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost:8080", true);
xhttp.send("sometexthere");

这将发送到我的 Node.js 服务器。到目前为止,我已经能够很好地响应这些请求。但是,现在我想访问我服务器上的“sometexthere”。

var express = require('express')
var app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

//some other stuff 

app.post('/', function(req, res) {
      //How do I access the text sent in xhttp.send()
}

我尝试过使用 req.body 和 req.query。但是,所有这些值都显示为空。如何使用 xhttp.send() 发送文本,然后从 Express 中的 req 对象中获取它?

谢谢!

【问题讨论】:

    标签: javascript ajax node.js express


    【解决方案1】:

    尝试为您的 AJAX 请求设置标头

    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    

    然后你就可以在 req.body 中阅读了

    【讨论】:

    • 谢谢!这与其他建议一起奏效。
    【解决方案2】:

    试试这样发送

    xhttp.send("foo=bar&lorem=ipsum");
    

    【讨论】:

    • 我如何访问它? req.body?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    相关资源
    最近更新 更多