我对后端和 express 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
,但它不起作用。
它甚至说:
从来源“http://127.0.0.1:5500”获取“http://localhost:3500/”的访问已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin” header 在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。 index.html:12 GET http://localhost
最佳答案
因为你的前端服务地址端口和后端服务地址端口不一样,Cross-Origin Resource Sharing被触发。这就是您在浏览器控制台中收到错误的原因。
为了启用 CORS,我们可以使用 cors中间件。
或者,使用 http-proxy-middleware将您的 API 代理到目标服务器。
前端 => 本地 HTTP 服务器 => 目标服务器。
关于javascript - 如何修复 GET net::ERR_FAILED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65340253/