NodeJS 对XMLHttpRequest的访问已被cors策略阻止:对预检请求的响应未通过访问控制检查

qni6mghb  于 2023-08-04  发布在  Node.js
关注(0)|答案(2)|浏览(93)

错误:

Access to XMLHttpRequest at 'http://localhost:8000/hirings/hiring' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

字符串

header

app.use((req,res,next)=>{
    res.header('Access-Control-Allow-Headers, *, Access-Control-Allow-Origin', 'Origin, X-Requested-with, Content_Type,Accept,Authorization','http://localhost:4200');
    if(req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods','PUT,POST,PATCH,DELETE,GET');
        return res.status(200).json({});
    }
    next();
});

app.use(cors());


请给予这个问题的解答

pxyaymoc

pxyaymoc1#

在express框架中,中间件的顺序是很重要的。您可以按如下方式修复它:

app.use(cors());
app.use((req,res,next)=>{
    res.header('Access-Control-Allow-Headers, *, Access-Control-Allow-Origin', 'Origin, X-Requested-with, Content_Type,Accept,Authorization','http://localhost:4200');
    if(req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods','PUT,POST,PATCH,DELETE,GET');
        return res.status(200).json({});
    }
    next();
});

字符串

dauxcl2d

dauxcl2d2#

在我的示例中,我使用CloudFront分发版来部署S3上的UI代码。从S3,UI代码请求转到API服务器,我在浏览器控制台中遇到了相同的错误。这是误导,表明CORS问题,但根本原因是CloudFront无法连接到源站。因此,必须检查源站的健康状况和可达性,以解决此问题。

相关问题