Node.js NodeJS-向远程主机发出HTTP请求时引发ERR_INVALID_ARG_类型错误

Node.js NodeJS-向远程主机发出HTTP请求时引发ERR_INVALID_ARG_类型错误,node.js,request,remote-server,request-promise,remote-host,Node.js,Request,Remote Server,Request Promise,Remote Host,最近,我在尝试使用NodeJS和发出请求时遇到了一个问题 以下代码嵌套在文件上载的multer调用中(使用嵌套函数/集群) const options = { method: 'POST', uri: 'URL of your choice', body: { //Body of the request }, // json: true, headers: {

最近,我在尝试使用NodeJS和发出请求时遇到了一个问题

以下代码嵌套在文件上载的multer调用中(使用嵌套函数/集群)

    const options = {
        method: 'POST',
        uri: 'URL of your choice',
        body: {
            //Body of the request
        },
        // json: true,
        headers: {
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
    }

    request(options)
        .then(function (response) {
            console.log('Response: ', response);

        })
        .catch(function (err) {
            console.log('Error: ', err);
        });
在使用当前请求时,如果没有“json:true”属性(注释掉),我会得到以下错误:

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type object
    at write_ (_http_outgoing.js:603:11)
    at ClientRequest.write (_http_outgoing.js:575:10)
    at Request.write (PATH/node_modules/request/request.js:1500:27)
    at end (PATH/node_modules/request/request.js:549:18)
    at Immediate.<anonymous> (PATH/node_modules/request/request.js:578:7)
    at runCallback (timers.js:696:18)
    at tryOnImmediate (timers.js:667:5)
    at processImmediate (timers.js:649:5)
    at process.topLevelDomainCallback (domain.js:121:23)
TypeError[ERR\u INVALID\u ARG\u TYPE]:第一个参数必须是string或Buffer.Received类型的对象之一
在写入时(_http_outgoing.js:603:11)
在ClientRequest.write(_http_outgoing.js:575:10)
at Request.write(PATH/node_modules/Request/Request.js:1500:27)
最后(PATH/node_modules/request/request.js:549:18)
立即。(PATH/node_modules/request/request.js:578:7)
运行回调时(timers.js:696:18)
在tryOnImmediate(timers.js:667:5)
在processImmediate(timers.js:649:5)
在process.topLevelDomainCallback(domain.js:121:23)
当我打开“json:true”选项时,问题不会发生,但是远程API返回一个错误,因为它不能很好地处理json请求/它们添加的花括号

关于克服这个问题有什么想法吗

谢谢。

试试下面的内容-

url = "your url"
const options = {
  url: url,
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Accept-Charset': 'utf-8'
  },

  body: {

  }
};
request.post(options, function (err, response, body) {
      // do something with your data
console.log(response.statusCode);
console.log(body)
});
解决了它!
由于远程主机不能很好地处理JSON,并且需要发送“普通”POST请求,所以我再次查看了RequestPromise的文档。 通过将
body{}
更改为
formData{}
,并注释掉
json:true
,问题得到了解决

const options = {
    method: 'POST',
    uri: 'URL of your choice',
    formData: {
        //Request's data
    },
}

request(options)
    .then(function (response) {
        console.log('Response: ', response);

    })
    .catch(function (err) {
        console.log('Error: ', err);
    });

我遇到了类似的问题,对于我的情况,上载目录没有正确定义,请确保您要上载文件的路径存在并且定义清楚