简体   繁体   English

使用Node.js / Express访问AJAX POST数据

[英]Access AJAX POST data with Node.js/Express

I'm building a web application that uses Node.js/Express for the backend. 我正在构建一个使用Node.js / Express作为后端的Web应用程序。

In my front end, I am sending an AJAX request to the server through Javascript that looks likes this: 在我的前端,我通过Javascript向服务器发送一个AJAX请求,看起来像这样:

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

This goes to my Node.js server. 这发送到我的Node.js服务器。 So far, I have been able to respond to these requests perfectly fine. 到目前为止,我已经能够完美地回应这些要求。 However, now I want to access the "sometexthere" on my server. 但是,现在我想访问我服务器上的“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()
}

I've tried using req.body and req.query. 我尝试过使用req.body和req.query。 However, all of those values show up empty. 但是,所有这些值都显示为空。 How do I send text with xhttp.send() and then get it from the req object in Express? 如何使用xhttp.send()发送文本,然后从Express中的req对象获取文本?

Thanks! 谢谢!

试试这样发送它

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

Try setting header to your AJAX request 尝试为您的AJAX请求设置标头

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

then you will able to read in req.body 然后你就可以阅读req.body了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM