我如何获得通过Ajax POST发送到Nodejs Server中的数据?
//客户端 $阿贾克斯({ 网址:'/ getExp, 数据:'IDK请告诉我RC, 键入:POST, }); //服务器 app.post('/ getExp',功能(REQ,RES){ VAR数据= REQ ???。 //我想要的数据等于IDK请告诉我RC }解决方案
防爆preSS 4.x的:
防爆preSS 4不再包含连接为一个依赖,这意味着你将需要单独安装机体解析模块。
解析器中间件可以在自己的GitHub的资源库这里找到。它可以安装像这样:
NPM安装体分析器有关表单数据,这是怎样的中间件将用于:
VAR bodyParser =需要('身体解析器'); app.use(bodyParser.urlen codeD());
防爆preSS 3.x和之前:
您需要使用 bodyParser()中间件在Ex preSS它分析你的HTTP请求的原始体。中间件,然后填充 req.body 。
app.use(如press.bodyParser()); app.post('/路径,功能(REQ,RES){ 执行console.log(req.body); });您可能想传递一个字符串的对象,而不是你的POST请求,因为你现在有会出来这样的:
{IDK请告诉我RC':''}
使用code有点像这样的:
$。阿贾克斯({ 网址:'/ getExp, 数据:{STR:'IDK请告诉我RC}, 键入:POST, });
会得到你这样的:
{STR:'IDK请告诉我RC'}How do I access the data sent to a Nodejs Server via Ajax POST?
//Client $.ajax( { url: '/getExp', data: 'Idk Whats Rc', type: 'POST', }); //Server app.post('/getExp', function(req, res){ var data = req.???; //I want data to be equal to 'Idk Whats Rc' }解决方案
Express 4.x:
Express 4 no longer contains Connect as a dependency, which means you will need to install the body parsing module separately.
The parser middleware can be found at its own GitHub repository here. It can be installed like so:
npm install body-parserFor form data, this is how the middleware would be used:
var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded());
For Express 3.x and before:
You need to use the bodyParser() middleware in Express which parses the raw body of your HTTP request. The middleware then populates req.body.
app.use(express.bodyParser()); app.post('/path', function(req, res) { console.log(req.body); });You might want to pass an object instead of a string to your POST request because what you currently have will come out like this:
{ 'Idk Whats Rc': '' }Using code somewhat like this:
$.ajax({ url: '/getExp', data: { str: 'Idk Whats Rc' }, type: 'POST', });Will get you this:
{ str: 'Idk Whats Rc' }
更多推荐
通过Ajax POST发送到NodeJS服务器访问数据
发布评论