【问题标题】:how to fix GET net::ERR_FAILED如何修复 GET net::ERR_FAILED
【发布时间】:2021-03-28 02:48:18
【问题描述】:

我对后端和表达 js 非常陌生。我想从我的 rest api 中获取数据,但它正在发送这个错误 net::ERR_FAILED。

//my api

const express = require("express");
const app = express();
app.get("/", (req, res)=>{
    res.send("hello world!!!")
})
const videos = {
    "source": "....com",
    "url": "...com"
}
app.get("/api/home", (req, res)=>{
    res.send(videos)
})
app.listen(3500, ()=>console.log("listening at port 3500..."))
<!DOCTYPE html>
<html>
    <head>
        <title>Hey</title>
    </head>
    <body>
        <button onclick="init()">hey</button>
        
        <script>
            function init(){
                const url = "http://localhost:3500/api/home"
                fetch(url).then(res=>res.json()).then(result=>{
                    console.log(result)
                })
            }
        </script>
    </body>
</html>

我想在单击按钮时从 api 控制台记录数据 videos,但它不起作用。

它甚至说:

CORS 策略已阻止从源“http://127.0.0.1:5500”获取“http://localhost:3500/”的访问权限:不存在“Access-Control-Allow-Origin”标头在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。 index.html:12 获取 http://localhost

【问题讨论】:

  • 检查this。它来自官方 Express 文档。您可以在开发/测试后端时启用所有来源,然后在生产发布之前在那里设置您的域名。这只会允许来自该来源的流量由您的后端进一步处理。

标签: javascript ajax express http server


【解决方案1】:

因为你的前端服务地址端口和后端服务地址端口不同,所以触发Cross-Origin Resource Sharing。这就是您在浏览器控制台中出现错误的原因。

为了启用CORS,我们可以使用cors中间件

【讨论】:

    【解决方案2】:

    我有类似的问题。 检查您机器上的 /etc/hosts 并 尝试添加(如果不存在) 127.0.0.1 本地主机

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-27
      • 2020-06-23
      • 2021-01-08
      • 2020-05-26
      • 2020-12-30
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多