在Node.JS中向HTTP POST请求添加参数

编程入门 行业动态 更新时间:2024-10-25 18:32:14
本文介绍了在Node.JS中向HTTP POST请求添加参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经知道使用Node.js发送简单HTTP请求的方法如下:

I've known the way to send a simple HTTP request using Node.js as the following:

var http = require('http'); var options = { host: 'example', port: 80, path: '/foo.html' }; http.get(options, function(resp){ resp.on('data', function(chunk){ //do something with chunk }); }).on("error", function(e){ console.log("Got error: " + e.message); });

我想知道如何在 POST的主体中嵌入参数请求以及如何从接收器模块捕获它们。

I want to know how to embed parameters in the body of POST request and how to capture them from the receiver module.

推荐答案

你介意使用请求库。发送帖子请求就像

Would you mind using the request library. Sending a post request becomes as simple as

var options = { url: 'someurl', 'method': 'POST', 'body': {"key":"val"} }; request(options,function(error,response,body){ //do what you want with this callback functon });

请求库还有一个快捷方式,可以在 request.post中发布帖子您传递网址以发送帖子请求以及要发送到该网址的数据的方法。

The request library also has a shortcut for post in request.post method in which you pass the url to make a post request to along with the data to send to that url.

根据评论进行修改

要捕获一个帖子请求,它会如果您使用某种框架,那就最好了。由于 express 是最受欢迎的,我将以快递为例。如果您不熟悉快递,我建议您阅读作者自己的入门指南 。

To "capture" a post request it would be best if you used some kind of framework. Since express is the most popular one I will give an example of express. In case you are not familiar with express I suggest reading a getting started guide by the author himself.

您需要做的就是创建一个邮政路线,回调函数将包含发布到该网址的数据

All you need to do is create a post route and the callback function will contain the data that is posted to that url

app.post('/name-of-route',function(req,res){ console.log(req.body); //req.body contains the post data that you posted to the url });

更多推荐

在Node.JS中向HTTP POST请求添加参数

本文发布于:2023-10-12 00:11:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483232.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中向   参数   JS   Node   HTTP

发布评论

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

>www.elefans.com

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