簡體   English   中英

相當於這個curl請求的Node.js

[英]Node.js equivalent of this curl request

我正在嘗試使用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請求時,無法正常工作。 我在Unirest的Node庫中進行了嘗試。 這是我使用的代碼:

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

或使用所需的任何用戶代理。

與超級代理:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM