如何使用NodeJS在POST请求中发送JSON

时间:2017-08-30 08:45:28

标签: json node.js request

我正在尝试向接受JSON的端点发送POST请求但它不起作用。我是否必须发送任何特定参数才能让网络知道它被编码为JSON?

这是我到目前为止的简单要求:

var request = require('request')

var cookie = '**Here the cookie copied from the Network tab from the Chrome Dev Tools Bar**'
var UA = '**Here the UA copied from the Network tab from the Chrome Dev Tools Bar**'

var JSONformData = {"jsonrpc":"2.0","method":"LMT_split_into_sentences","params":{"texts":["Text"],"lang":{"lang_user_selected":"auto","user_preferred_langs":["EN","ES"]}},"id":8}

var URL = 'https://www.deepl.com/jsonrpc'

request.cookie(cookie)
request.post({
        url: URL, 
        headers: {
            'User-Agent': UA
        },
        form: JSONformData
    }, function(error, response, body) {
        console.log(response)
    }
)

1 个答案:

答案 0 :(得分:5)

如果要发送JSON数据,则无需指定表单,而是在options对象中为数据指定json:

request.post({
        url: URL, 
        headers: {
            'User-Agent': UA
        },
         json: JSONformData
    }, function(error, response, body) {
        console.log(response)
    })