DjB*_*ial 2 javascript ajax http express server
我对后端和 Express js 非常陌生。我想从我的其余 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..."))Run Code Online (Sandbox Code Playgroud)
<!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>Run Code Online (Sandbox Code Playgroud)
我想在单击按钮时控制台记录来自 api 的数据videos,但它不起作用。
它甚至说:
从源“http://127.0.0.1:5500”获取“http://localhost:3500/”的访问已被 CORS 策略阻止:请求中不存在“Access-Control-Allow-Origin”标头资源。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。index.html:12 获取 http://localhost
因为你的前端服务地址端口和后端服务地址端口不一样,跨源资源共享触发了这就是您在浏览器控制台中收到错误的原因。
为了启用CORS,我们可以使用cors中间件。
或者,使用http-proxy-middleware将您的 API 代理到目标服务器。
前端 => 本地 HTTP 服务器 => 目标服务器。