【发布时间】: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