Cors 已启用但仍然得到这个 "Origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present "
Cors enabled but Still got this "Origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present "
我试图从后端重定向浏览器,但每次都出现此 cors 错误。在后端,我使用了CORS包,但是,它似乎没有用。
这里是代码的客户端
useEffect(() => {
async function getData() {
try {
// The params get from the url.
const {
data
} = await axios.get(`http://localhost:5000/${url}`);
setDestination(data);
} catch (error) {
setError(error.message);
}
}
getData();
}, [url]);
useEffect(() => {
if (destination) {
window.location.replace(destination);
}
}, [destination]);
这里是代码的服务器站点
// app.js
const express = require("express");
const cors = require("cors");
const app = express();
app.use(express.urlencoded({
extended: false
}));
app.use(express.json());
app.use(cors());
//redirect controller
exports.redirect = asyncErrorHandler(async(req, res, next) => {
const shortUrl = await urlSchema.findOne({
shortUrl: req.params.shortUrl
});
if (!shortUrl) {
return next(new ErrorHandler("Invalid URL", 404));
}
const url = shortUrl.fullUrl;
res.redirect(url);
});
您向我们展示的服务器端代码在启用 CORS 时重定向到另一个 URL。
重定向重定向响应和对后续请求的响应时,必须使用 CORS 授予权限。
您不能通过向 http://mine.example.net/
(已启用)发出请求并重定向至 http://third-party.example.com/
.
我试图从后端重定向浏览器,但每次都出现此 cors 错误。在后端,我使用了CORS包,但是,它似乎没有用。
这里是代码的客户端
useEffect(() => {
async function getData() {
try {
// The params get from the url.
const {
data
} = await axios.get(`http://localhost:5000/${url}`);
setDestination(data);
} catch (error) {
setError(error.message);
}
}
getData();
}, [url]);
useEffect(() => {
if (destination) {
window.location.replace(destination);
}
}, [destination]);
这里是代码的服务器站点
// app.js
const express = require("express");
const cors = require("cors");
const app = express();
app.use(express.urlencoded({
extended: false
}));
app.use(express.json());
app.use(cors());
//redirect controller
exports.redirect = asyncErrorHandler(async(req, res, next) => {
const shortUrl = await urlSchema.findOne({
shortUrl: req.params.shortUrl
});
if (!shortUrl) {
return next(new ErrorHandler("Invalid URL", 404));
}
const url = shortUrl.fullUrl;
res.redirect(url);
});
您向我们展示的服务器端代码在启用 CORS 时重定向到另一个 URL。
重定向重定向响应和对后续请求的响应时,必须使用 CORS 授予权限。
您不能通过向 http://mine.example.net/
(已启用)发出请求并重定向至 http://third-party.example.com/
.