javascript - Nodejs http.request 如何将 json 参数发送到 java 接口(interface)

标签 javascript java node.js json

我们有一个java接口(interface)来发送verify_code到手机,并且在postman上工作得很好。

postman

我的nodejs代码如下

let test = {
        "phoneNumber": "15021071273",
        "smsParams": [
            "注册",
            "123456",
            "注册"
        ],
        "tmplId": 109341
    }

    var content = JSON.stringify(test);

    // An object of options to indicate where to post to
    var post_options = {
        host: '172.16.211.33', //'common-message'
        port: '10011',
        path: '/sms/sendTecentyunSms',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': content.length
        }
    };

    // Set up the request
    var post_req = http.request(post_options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('Response: ' + chunk);
        });
    });

    // post the data
    post_req.write(content);
    post_req.end();

和java接口(interface)响应:

Response: {"timestamp":1572935973619,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"JSON parse error: Unexpected end-of-input within/between Object entries; nested exception is com.fasterxml.jackson.core.io.JsonEOFException: Unexpected end-of-input within/between Object entries\n at [Source: java.io.PushbackInputStream@3e497877; line: 1, column: 157]","path":"/sms/sendTecentyunSms"}

看起来这只是一个 json 解析错误。

我还尝试先对 tese.smsParams 进行 JSON.stringy,但不起作用

req.write 只接受字符串或缓冲区,因此它不能只将 json 对象作为参数。

最佳答案

请尝试这个方法

var http = require('http')

var body = JSON.stringify({
        "phoneNumber": "15021071273",
        "smsParams": [
            "注册",
            "123456",
            "注册"
        ],
        "tmplId": 109341
    })

var request = new http.ClientRequest({
    hostname: "172.16.211.33",
    port: 10011,
    path: "/sms/sendTecentyunSms",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(body)
    }
})

request.end(body)


request.on('response', function (response) {
  console.log('STATUS: ' + response.statusCode);
  console.log('HEADERS: ' + JSON.stringify(response.headers));
  response.setEncoding('utf8');
  response.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

关于javascript - Nodejs http.request 如何将 json 参数发送到 java 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58705899/

相关文章:

javascript - Ruby on Rails - 使用 AJAX 更新输入选择选项

javascript - 在异步函数内或 Promise 内设置全局变量的值?

java - 空对象引用工具栏android

java - 使用 textview 更新文本时出现问题

javascript - 如何在 Leaflet.js 中使用 Angular JS

node.js - 纽约 + Mocha + es6 模块

javascript - 在 Jade 中,如何调用外部 Javascript 中的函数

javascript - 一年中的某一天集成到 jquery ui 日期选择器中

java - 持续解析和处理文本

javascript - Webrtc 将 ice 候选者添加到远程对等点