类型错误 "string" 必须是字符串、缓冲区或数组缓冲区。

4
我在Node中尝试向一个端点发送http请求,但没有得到任何响应。我确信自己设置有误。我的请求在Postman上有效。请帮忙解决!
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

curlUpdate = function curlUpdate() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "www.example.com", false);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send({
        FirstName: "john",
        LastName: "doe",
        MerchantSessionID: "817281271",
        DateOfBirth: "12,24,1985",
        ProductTypeID: "xxxxxxxxx"
    });
    console.log(xhr.responseText);
};

1
我认为你应该传递一个字符串到 send 而不是一个对象。在将其传递给 send 之前,尝试使用 JSON.stringify 将对象转换为字符串。 - ibrahim mahrir
是的,看起来可以运行,谢谢!@ibrahimmahrir - Nish
1个回答

3

你只需要使用JSON.stringify()将对象包装起来。

这样,你的xhr.send看起来会像这样:

xhr.send(JSON.stringify({
        FirstName: "john",
        LastName: "doe",
        MerchantSessionID: "817281271",
        DateOfBirth: "12,24,1985",
        ProductTypeID: "xxxxxxxxx"
    }));

顺便提一句,不要忘记在代码中将地址(现在是www.example.com)指向正确的终端点。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接