如何在"请求"npm包中设置内容类型

Ash*_*Jha 2 javascript request node.js

我从节点服务器发送请求到其他服务器,但我需要发送内容类型

应用程序/ JSON

我怎么发送,我使用这种格式

request.post('https://server.com/index.php/rest/V1/integration/admin/token',{form:postData},function (error, response, body) {
    console.log('error:', error); // Print the error if one occurred
    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
    console.log('body:', body); // Print the HTML for the Google homepage.
    res.json({
        'error': error,
        'statusCode': response && response.statusCode,
        'body': body
    })
});
Run Code Online (Sandbox Code Playgroud)

我在尝试这个时遇到错误

 request.post(
        'https://server.com/index.php/rest/V1/integration/admin/token',
        {
            form:postData,
            headers:{ 
                "Content-Type": "application/json"
            }

    },function (error, response, body) {
        console.log('error:', error); // Print the error if one occurred
        console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
        console.log('body:', body); // Print the HTML for the Google homepage.
        res.json({
            'error': error,
            'statusCode': response && response.statusCode,
            'body': body
        })
    });
Run Code Online (Sandbox Code Playgroud)

"message":"服务器无法理解Content-Type HTTP标头媒体类型application/x-www-form-urlencoded"

Man*_*kur 6

请更改键名 formjson.

    request.post('https://server.com/index.php/rest/V1/integration/admin/token', {
    json: postData
}, function(error, response, body) {
    console.log('error:', error); // Print the error if one occurred
    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
    console.log('body:', body); // Print the HTML for the Google homepage.
    res.json({
        'error': error,
        'statusCode': response && response.statusCode,
        'body': body
    })
});
Run Code Online (Sandbox Code Playgroud)