【问题标题】:Node.js equivalent of this curl request此 curl 请求的 Node.js 等效项
【发布时间】:2016-11-16 20:14:54
【问题描述】:

我正在尝试使用HTML validator 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.js 的 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 为空。我不知道我做错了什么,并希望得到任何帮助。

【问题讨论】:

    标签: javascript node.js curl w3c-validation


    【解决方案1】:

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

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

    或者使用任何你想要的用户代理。

    【讨论】:

    • 这个做到了。谢谢。
    • 超级代理必须自动添加用户代理标头,这可以解释为什么我的示例“正常工作”而无需执行任何特殊操作。
    • @Kevin 是的,很多 http 客户端会自动添加用户代理标头以实现兼容性(与 w3.org 等网站)。 Curl 也这样做,这就解释了为什么问题中的 curl 命令有效。
    【解决方案2】:

    有超级代理:

    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));
        });
    

    【讨论】:

      猜你喜欢
      • 2014-07-01
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 2011-10-12
      • 1970-01-01
      • 2018-10-31
      • 2015-05-25
      相关资源
      最近更新 更多