node.js - 核心 https 库与 npm 'request' 库
问题描述
尝试使用内置节点 https 库时遇到了一个非常奇怪的问题。
请求标头:
let requestDetails = {
hostname: 'api.domain.com',
method: 'POST',
path: '/endpointIWant/goHere
headers: {
'Client-ID': clientId,
'Content-Type': 'application/json',
Authorization: bearerToken
},
};
请求正文:
let body = JSON.stringify({
"content_type": "application/json",
"message" : message
});
这是我使用默认 https 节点库的标准调用:
let req = https.request(requestDetails, function (res){
let responseBody = undefined;
res.on('body', function(res) {
responseBody = '';
});
res.on('data', function(chunk) {
responseBody += chunk;
});
res.on('end', function() {
console.log(responseBody);
});
});
req.write(body);
req.on('error', function(e) {
console.log(e);
});
req.end();
现在,每当我将此请求发送到相关服务器时,我都会得到:
Your browser sent a request that this server could not understand.
Reference #7.24507368.1554749705.3185b29b
但是,当我在 NPM 上使用流行的“请求”库时,它运行良好,并且得到了我期望的响应。
这导致人们相信这两个库之间请求的“编码”或“分块”可能有所不同,但我不知道是什么。
有没有人有 Node https 库的经验并理解那里的任何问题?
我更喜欢尽可能使用内置库来保持我的包大小。
解决方案
当使用本机http或https模块时,您需要使用 querystring 模块来字符串化您的正文。
const querystring = require('querystring');
let body = querystring.stringify({
"content_type": "application/json",
"message" : message
});
//also include the content length of your body as a header
let requestDetails = {
hostname: 'api.domain.com',
method: 'POST',
path: '/endpointIWant/goHere
headers: {
'Client-ID': clientId,
'Content-Type': 'application/json',
'Content-Length' : body.length
Authorization: bearerToken
},
};
'request'构建在本机模块之上,并在您向其传递 json 正文时在内部执行此操作
推荐阅读
- java - 存储过程在使用 java 调用时不起作用,但是当我手动执行它时
- winapi - WinAPI CreateDialog 资源未找到错误 0x715
- ansible - 使用 init.d 文件的自定义路径重新启动服务
- java - 为什么 Java Graphics 不能与自定义子类一起使用?
- powerbi - 停止从用户端重新共享bi报告
- c# - 如何在 C# Webservices 中公开 3 个端点?
- java - 无法在android中工作windowsoftinputmode
- autodesk-forge - 查看 API BIM360 的附件(图像)时出现问题
- ruby-on-rails - Will_paginate 错误未定义方法“total_pages”
- nginx - Kubernetes 上的 UDP 负载平衡 (AKS)