使用请求从NodeJS进行发布

时间:2019-02-20 19:12:14

标签: node.js

我通过nodeJs应用程序的请求发布json文档时遇到问题。 对我来说,问题是如何通过json文档进行发布。这是对我有用的

const options = {  
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,

body: { "message": {
    "subject": "Meet for lunch?",
    "body": {
      "contentType": "html",
      "content": "</p>\r\n\r\n<ul type=\"disc\">\r\n\t<li><strong>Ready to Use Experiences</strong> &ndash; Get instant access to our fully configured and integrated environments allowing you to use and experience the products as a customer would in their own deployment. We&rsquo;ve set up the products alongside partner solutions so you can experience the entire ecosystem including Office 365, Salesforce, and more.&nbsp;</li>\r\n</ul>"
    },
    "toRecipients": [
      {
        "emailAddress": {
          "address": "test@ueser.com"
        }} ]}}}




request(options, function(err, res, body) {  
console.log(res.statusCode)
})

我遇到的问题是,如果我想从这样的字符串中传递正文

var mybody = `{ "message": {
"subject": "Meet for lunch?",
"body": {
  "contentType": "html",
  "content": "This is a test"
},
"toRecipients": [
  {
    "emailAddress": {
      "address": "test@user.com"
    }
}]}}`

然后这样称呼它

const options = {  
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,

body: mybody
}

request(options, function(err, res, body) {  
console.log(res.statusCode)
})

会引发类似

的错误
  

SyntaxError:JSON中位置0处出现意外令牌

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用stringify? Node.js有一个名为querystring的内置模块。

const querystring = require("querystring");
const myStringBody = querystring.stringify(myBody);

然后将其写入您的请求。

req.write(myStringBody);