为什么我使用 https.request 获得状态 400。如果我使用 https.get 我没有问题,但我也希望能够发送帖子 requests (不依赖于 fetch 或 axios)!
这是我的代码
const options = {
hostname: 127.0.0.1,
path: api/hubert,
method: 'POST',
port: 3000,
// headers: {
// 'Content-Type': 'application/json'
// },
};
const testMethod = (options) => new Promise((resolve, reject) => {
req = http.request(options, (res) => {
const chunks = []
res.on('data', chunk => chunks.push(chunk))
res.on('error', reject)
res.on('end', () => {
const { statusCode, headers } = res;
const body = chunks.join('')
console.log("resolving")
resolve({ statusCode, headers, body })
})
})
console.log("request")
console.log(req.headers)
req.end()
})
驱动程序代码:
testMethod(options).then(response => {
console.log("response!")
console.log(response)
产生:
{ statusCode: 400, headers: { connection: 'close' }, body: '' }
该 api 只是一个基本的 nextjs api(见下文),位于 api/hubert.js 内容是垃圾我只希望它识别我的帖子 request 和控制台日志 john doe - 然后我知道我正在正确构建我的 request Node。
export default function handler(req, res) {
if (req.method === 'POST') {
console.log(req)
res.status(200).json({ name: 'John Doe' })
} else {
console.log(req);
res.status(200).json({error: 'Method not allowed' })
}
}
回答1
我在路径前需要一个正斜杠
const options = {
hostname: 127.0.0.1,
path: '/api/hubert',
method: 'POST',
port: 3000,
// headers: {
// 'Content-Type': 'application/json'
// },
};