Rad*_*lav 109 post curl node.js
我们如何在NodeJS中发出这样的HTTP请求?示例或模块表示赞赏.
curl https://www.googleapis.com/urlshortener/v1/url \
-H 'Content-Type: application/json' \
-d '{"longUrl": "http://www.google.com/"}'
Run Code Online (Sandbox Code Playgroud)
Jos*_*ith 273
Mikeal的请求模块可以轻松完成:
var request = require('request');
var options = {
uri: 'https://www.googleapis.com/urlshortener/v1/url',
method: 'POST',
json: {
"longUrl": "http://www.google.com/"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body.id) // Print the shortened url.
}
});
Run Code Online (Sandbox Code Playgroud)
小智 11
简单的例子
var request = require('request');
//Custom Header pass
var headersOpt = {
"content-type": "application/json",
};
request(
{
method:'post',
url:'https://www.googleapis.com/urlshortener/v1/url',
form: {name:'hello',age:25},
headers: headersOpt,
json: true,
}, function (error, response, body) {
//Print the Response
console.log(body);
});
Run Code Online (Sandbox Code Playgroud)
小智 9
正如官方文件所说:
body - PATCH,POST和PUT请求的实体主体.必须是Buffer,String或ReadStream.如果json为true,则body必须是JSON可序列化对象.
发送JSON时,您只需将其放在选项的正文中即可.
var options = {
uri: 'https://myurl.com',
method: 'POST',
json: true,
body: {'my_date' : 'json'}
}
request(options, myCallback)
Run Code Online (Sandbox Code Playgroud)
Axios更少但更好:
const data = JSON.stringify({
message: 'Hello World!'
})
const url = "https://localhost/WeatherAPI";
axios({
method: 'POST',
url,
data: JSON.stringify(data),
headers:{'Content-Type': 'application/json; charset=utf-8'}
})
.then((res) => {
console.log(`statusCode: ${res.status}`)
console.log(res)
})
.catch((error) => {
console.error(error)
})
Run Code Online (Sandbox Code Playgroud)
另请检查在 Node.js 中发出 HTTP 请求的 5 种方法
https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html
参考:
https://nodejs.dev/learn/make-an-http-post-request-using-nodejs
https://flaviocopes.com/node-http-post/
https://stackabuse.com/making-asynchronous-http-requests-in-javascript-with-axios/
| 归档时间: |
|
| 查看次数: |
128200 次 |
| 最近记录: |