【问题标题】:Fetch working in HTML page but not in JS one [duplicate]获取在 HTML 页面中工作但不在 JS 中工作 [重复]
【发布时间】: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'
    }

【问题讨论】:

    标签: node.js cors fetch


    【解决方案1】:

    来自浏览器的请求正在发送一些标头,例如用户代理(该库默认为setting to node-fetch

    由于 403 的原因,您必须检查您的请求响应,并查看 API 文档以获取更多说明。

    【讨论】:

    • 有没有办法查看发送的headers
    • 在浏览器中,检查开发工具的网络选项卡。在节点获取中,see docs
    • 我知道这个选项,但是 .js 文件中的那个没有被浏览器捕获,因为没有打开网站(只有后端代码)。
    • 我知道 ^^ 这就是为什么只设置默认标题的原因。例如,尝试发送浏览器发送的所有标头,看看是否也收到 403!
    • 更新了我最初的帖子,添加的标题仍然被 CloudFare 卡住
    猜你喜欢
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 2018-07-15
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多