相当于这个curl请求的Node.js

Node.js equivalent of this curl request

本文关键字:Node js 请求 curl 相当于      更新时间:2023-09-26

我正在尝试使用HTML验证器API。curl示例对我来说工作得很好,我可以将它们作为子进程在Node中运行。下面是它的代码:

var command = ('curl -H "Content-Type:text/html; charset=utf-8" --data-binary @' + file + 
' https://validator.w3.org/nu/?out=json');
exec(command, function(err1, out, err2) {
    console.log(out);
    console.log('done');
});

然而,当我尝试使用标准的HTTP请求时,我无法使其工作。我尝试使用Node的Unirest库。下面是我使用的代码:

var source = '<html><head><title>a</title></head><body>a</body></html>';
var url = 'http://validator.w3.org/nu/?out=json';

var Request = unirest.post(url);
Request.headers({'Content-Type': 'text/html', 'charset': 'utf-8'});
Request.send(source);
Request.end(res => console.log(res));

响应体未定义,响应raw_body为空。我不知道我做错了什么,希望你能帮助我。

如果没有user-agent标头,validator.w3.org似乎不会响应请求。添加标题:

Request.headers({'Content-Type': 'text/html; charset=utf-8', 'user-agent': 'Node.js'});

或者使用您想要的任何useragent。

与超级代理:

const request = require('superagent');
const body = '<html><head><title>a</title></head><body>a</body></html>';
request.post('https://validator.w3.org/nu/?out=json')
    .set('Content-Type', 'text/html; charset=utf-8')
    .send(body)
    .end((err, res) => {
        console.log('got body: ' + JSON.stringify(res.body));
    });