[英]Express proxy + axios + cors: still cors issue
我用 express 創建了以下代理:
import express from "express";
import cors from "cors";
import proxy from "express-http-proxy";
const app = express();
app.use(
cors({
origin: "http://localhost:8081",
credentials: true,
})
);
app.use("/", proxy("http://my-website:8810"));
app.listen(3000, () => {
console.log("server listening on port 3000");
});
從前端我使用 axios:
axios.defaults.withCredentials = true;
const res = await axios.get("http://localhost:3000", {
auth: {
username: "xxxxx",
password: "xxxxx",
},
headers: {
"Content-Type": "application/json",
},
});
但我仍然有以下 cors 問題:
Access to XMLHttpRequest at ' http://my-website:8810 ' (redirected from ' http://localhost:3000/ ') from origin ' http://localhost:8081 ' has been blocked by CORS policy: Response to preflight請求未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”header。
在面對這個問題數小時后……我來了。 誰能向我解釋我在這里做錯了什么?
最后它通過使用“請求”來工作,例如:
app.use(
cors({
origin: "http://localhost:8081",
credentials: true,
})
);
router.get("/", (req, res) => {
request(
"http://my-website:8810",
{
auth: {
username: "node_proxy",
password: "password",
},
headers: { Accept: "application/json" },
},
(error, response, body) => {
res.send(body);
}
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.