Nov*_*ova 42 https post node.js
我正在开发一个需要https get和post方法的项目.我在这里有一个简短的https.get函数...
const https = require("https");
function get(url, callback) {
"use-strict";
https.get(url, function (result) {
var dataQueue = "";
result.on("data", function (dataBuffer) {
dataQueue += dataBuffer;
});
result.on("end", function () {
callback(dataQueue);
});
});
}
get("https://example.com/method", function (data) {
// do something with data
});
Run Code Online (Sandbox Code Playgroud)
我的问题是没有https.post,我已经在这里用https模块尝试了http解决方案如何在node.js中发出HTTP POST请求?但返回控制台错误.
我在浏览器中使用Ajax和Ajax发布到同一个api时没有问题.我可以使用https.get来发送查询信息,但我认为这不是正确的方法,如果我决定扩展,我认为它不会在以后发送文件.
是否有一个小的例子,有最低要求,使https.request成为https.post,如果有的话?我不想使用npm模块.
ari*_*ing 113
例如,像这样:
const querystring = require('querystring');
const https = require('https');
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'posttestserver.com',
port: 443,
path: '/post.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(postData);
req.end();
Run Code Online (Sandbox Code Playgroud)
Abo*_*zlR 20
告别node-fetch 包、axios和request ……现在fetch API 默认在全局范围内可用。
发布请求
app.get('/', (req, res, next) => {
// Make a post Request.
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch(error => {
console.log(error)
})
res.send('Fetch API is available on the global scope by default')
})
Run Code Online (Sandbox Code Playgroud)
获取请求
const res = await fetch('https://nodejs.org/api/documentation.json');
if (res.ok) {
const data = await res.json();
console.log(data);
}
Run Code Online (Sandbox Code Playgroud)
我们可以像在浏览器中一样发出请求。
这是一个与接受的答案略有不同的版本:
asyncx-www-form-urlencodedconst https = require('https')
async function post(url, data) {
const dataString = JSON.stringify(data)
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': dataString.length,
},
timeout: 1000, // in ms
}
return new Promise((resolve, reject) => {
const req = https.request(url, options, (res) => {
if (res.statusCode < 200 || res.statusCode > 299) {
return reject(new Error(`HTTP status code ${res.statusCode}`))
}
const body = []
res.on('data', (chunk) => body.push(chunk))
res.on('end', () => {
const resString = Buffer.concat(body).toString()
resolve(resString)
})
})
req.on('error', (err) => {
reject(err)
})
req.on('timeout', () => {
req.destroy()
reject(new Error('Request time out'))
})
req.write(dataString)
req.end()
})
}
const res = await post('https://...', data)
Run Code Online (Sandbox Code Playgroud)
console.log("trying ...")
let body = {
"ids": ["4e4e4e4e-4e4e-4e4e-4e4e-4e4e4e4e4e4e"]
};
fetch('https://blahblah.com/blah', {
method: 'POST',
body: JSON.stringify(body),
headers: {
'accept': 'application/json',
'x-api-key': 'superamazingsecretcryptostuff',
'Content-Type': 'application/json'
// fyi, NO need for content length
}
})
.then(res => res.json())
.then(json => console.log(json))
.catch (err => console.log(err))
console.log("done....")
Run Code Online (Sandbox Code Playgroud)
任务完成。
| 归档时间: |
|
| 查看次数: |
59808 次 |
| 最近记录: |