【问题标题】:Nodejs post Json data with headersNodejs 发布带有标头的 Json 数据
【发布时间】:2021-10-31 02:47:26
【问题描述】:

如何使用表单数据或请求通过节点 js 发布 Json 数据?

使用表单数据。 它不允许发送自定义标头,如果将 bodyParams.getHeaders() 替换为自定义标头,它不会发送请求数据 https://www.npmjs.com/package/form-data

        const smsResponse = await request.post(url, bodyParams, {headers:bodyParams.getHeaders()})

使用 Request 不允许发送参数 要求('请求');

  const subscription = await request.post(url, body, {headers:{'Accept':'text/html'}})

邮递员卷曲请求它通过邮递员工作。尝试使用 postman nodejs 请求代码但失败

curl --location --request POST 'https://personalsite.com//test.php' \
--header 'accept: text/html' \
--header 'SECRET-TOKEN-MESSAGE: dataforport' \
--header 'Content-Type: application/json' \
--header 'Cookie: PHPSESSID=1d2shuebo7lal8sn2itgppvfk4' \
--data-raw '{
  "mobileno": "888888888",
  "messagetext": "Test message"
}'

试过但没用 Node.js: How to send headers with form data using request module?

【问题讨论】:

  • 您收到的错误是什么?请求变量来自哪里?
  • @Florian 没有错误。如果您使用的是表单数据,它要么发送请求参数,要么发送自定义标头。在请求中它只发送标头但不发送参数。
  • @jfriend00 如何使用表单数据或请求通过节点 js 发布 Json 数据?已提供相关图书馆的链接

标签: node.js form-data


【解决方案1】:

使用new Headers() 构建您的标题。

https://developer.mozilla.org/en-US/docs/Web/API/Request/Request


var myHeaders = new Headers();
myHeaders.append('Accept', 'text/html');

var myInit = { method: 'POST',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default',
               body: JSON.stringify({coffee: 'yes...'})
 };

var myRequest = new Request('https://personalsite.com//test.php',myInit);

fetch(myRequest).then(function(response) {
  console.log(response)
});

【讨论】:

  • 如何在代码中传递参数。你测试过吗?我可以发送参数或标题,但我想同时传递参数和标题
  • 您可以JSON.stringify您的内容。也可以看看原生的new FormData
  • 我可以知道我必须安装多少个不同的库,1> Header 2> Request 和 3> fetch。请求 = 请求权?
  • 你不安装它们。它们是原生 Javascript 库。但我建议安装和使用 Axios 来发出请求。
猜你喜欢
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 2020-01-07
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 2018-03-28
相关资源
最近更新 更多