POST 请求返回 text/html 而不是 JSON,如何在 JS 中获取 JSON?

POST request returning text/html and not JSON, how do I get the JSON in JS?

为了工作,我们通过州网站验证选民登记。最近的更新打破了我们的验证。

他们现在需要 XSFR token/cookie。我已经能够使用下面的代码检索 cookie 并在 POST 请求中提交它。服务器以代码 200 响应。如果您注释掉 cookie/XSFR,您将看到它以 403 响应。

我正在使用请求模块。服务器响应 HTML/Text 文件,而不是像在浏览器中那样响应 JSON 文件。我究竟做错了什么?如果信息是错误信息,我已经包含了一些虚拟信息,服务器仍然使用 JSON 文件进行响应。如有任何帮助,我们将不胜感激!

我删除了我们用于验证选民的链接,并将它们替换为 Google.com 每个已修复的问题。

//using request module    npm install request --save

var request = require('request');
var jar = request.jar();
var request = request.defaults({
jar: jar,
});
var jar = request.jar();

// get cookie for XSRF token

request.get({
    url: 'https://www.google.com',
    method: 'get',
    jar: jar
}, () => {
    cookies = jar.getCookies('https://www.google.com');
    //output cookie
    console.log(cookies);
    var cookieToString = cookies.toString()
    //slice token for cookie response
    var xsrfCookie = cookieToString.slice(0, 47)
    //slice token for token response
    var slicedCookie = cookieToString.slice(11, 47)

    //send POST with xsrf token & cookie

    var request = require('request');
    var options = {

        uri: 'https://www.google.com',
        headers: {
            //custom HTTP headers for response
            Host: 'votesearch.google.com',
            'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0',
            Accept: 'application/json, text/plain, */*',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate, br',
            Referer: 'https://www.google.com',
            'Content-Type': 'application/json;charset=utf-8',
            'X-XSRF-TOKEN': slicedCookie,
            //'Content-Length': '118', leave commented out or server response hangs - not sure why
            Connection: 'keep-alive',
            Cookie: xsrfCookie,
            Pragma: 'no-cache',
            'Cache-Control': 'no-cache'
        },
        method: 'POST',
        json: {
            city: 'sometown',
            dob: '01-01-1950',
            firstName: 'John',
            lastName: 'Doe',
            street: '1234 street',
            zip: '12345'
        }
    }
    //server responsds with content type 'text/html' not JSON like in browser
    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body.id) // Print the shortened url - not working.
            console.log(response.headers); // can I get JSON from this?
            console.log(response.statusCode)


        } else {
            console.log('response code ' + response.statusCode);
            console.log('error ' + error)
        }
    });

})

当使用 request 模块发出请求时,为了在请求中包含 JSON 编码的请求主体,body 选项应设置为 JSON可序列化对象,json字段应设置为true.

json 字段设置为 true 还将确保将响应解析为 JSON 并在响应的 body 字段中可用。

在您的代码片段中的第二个请求中,json 字段设置为一个对象,该对象不是有效值。