【问题标题】:How to send JSON in a POST request with NodeJS如何使用 NodeJS 在 POST 请求中发送 JSON
【发布时间】:2018-02-07 21:35:19
【问题描述】:

我正在尝试向接受 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)
    }
)

【问题讨论】:

    标签: json node.js request


    【解决方案1】:

    如果你发送的是 JSON 数据,那么你不需要指定表单,而是在 options 对象中指定数据的 json:

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

    【讨论】:

    • 你的代码一定有问题。在此处查看文档:github.com/request/request#requestoptions-callback 使用 json 键指定 Json 数据会将内容类型设置为 json,将正文设置为 json 数据。
    • 如您所见:github.com/request/request#forms body: JSON.stringify(...) 这就是重点
    • 这有什么意义?他想用请求模块发送 Json 数据,这就是文档指定它完成的方式
    • @ÓscarAndreu 当您使用body: JSON.stringify 时,您需要将content-type 设置为application/json。但是当你将数据设置为json 字段时,请求会自动设置它。
    猜你喜欢
    • 2021-08-14
    • 2021-01-10
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2014-06-25
    相关资源
    最近更新 更多