【发布时间】:2021-07-26 17:01:00
【问题描述】:
非常简单的 HTML 页面通过 200 状态码获取我想要的 JSON:
<body>
<button id="login" name="login">login</button>
<script type="text/javascript">
document.getElementById('login').onclick = function () {
fetch('https://api.contonso.com/search/company',
{ method: 'GET' }).then(_ => console.log(_.status));
};
</script>
</body>
我以这种方式启动:
// index.js
const fs = require('fs');
var http = require('http');
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function (request, response) {
response.writeHeader(200, { "Content-Type": "text/html" });
response.write(html);
response.end();
}).listen(8000);
});
因此,在 HTML 页面中单击,获取与 console.log 打印 200 (OK) 一起使用。
现在考虑我正在使用以下代码修改index.js 中的代码:
// index.js (modified)
const fetch = require('node-fetch');
fetch('https://api.contonso.com/search/company',
{ method: 'GET' }).then(_ => console.log(_.status));
这里console.log 打印我403 (Forbidden)
你能解释一下我做错了什么吗?为什么它在 HTML 页面而不是 JS 页面中工作?
我正在开发一个不使用任何前端的机器人,我只需要 JS 文件。
谢谢,
仅在 JS 中我添加了以下标头(在 JS 中缺少的浏览器中看到),仍然是相同的错误
headers: {
'Origin': 'https://localhost:8000',
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
}
【问题讨论】: