我是非常新的后端和表达js。我想从rest中获取数据,但是它正在发送这个错误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://localhost:3500/‘获取'http://127.0.0.1:5500’的访问已被CORS策略阻止:请求的资源上没有“访问控制-允许-原产地”标题。如果不透明响应满足您的需要,请将请求的模式设置为“no- CORS”,以获取禁用CORS的资源。index.html:12 GET http://localhost
发布于 2020-12-18 04:26:21
由于前端服务地址端口和后端服务地址端口不同,因此会触发跨源资源共享。这就是浏览器控制台中出现错误的原因。
为了启用CORS,我们可以使用cors中间件。
或者,使用http-代理中间件将您的API代理到目标服务器。
前端=>本地HTTP服务器=>目标服务器。
发布于 2021-10-28 18:53:52
我也有过类似的问题。检查计算机上的/etc/host,并尝试添加(如果不存在) 127.0.0.1本地主机
https://stackoverflow.com/questions/65340253
复制相似问题