通过Ajax POST发送到NodeJS服务器访问数据

编程入门 行业动态 更新时间:2024-10-26 03:23:12
本文介绍了通过Ajax POST发送到NodeJS服务器访问数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我如何获得通过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-parser

For 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服务器访问数据

本文发布于:2023-10-10 22:27:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479931.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送到   服务器   数据   Ajax   POST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!