4

I use express.js for my server, with this headers:

x-powered-by: Express
connection: keep-alive
content-length: 2
content-type: application/json; charset=utf-8
access-control-allow-methods: GET,PUT,POST,DELETE
access-control-allow-origin: *
access-control-allow-headers: x-requested-with

I call res.header to allow CORS:

res.header("Access-Control-Allow-Origin:", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");  
res.header("Access-Control-Allow-Headers", "x-requested-with");

You can test here : http://my-api.rs.af.cm/api/products

For my front-end, I use jsbin and I call my server with $.ajax: http://jsbin.com/apizez/37/edit

Result here: http://jsbin.com/apizez/37

You can look at the JS console, you will see this error:

XMLHttpRequest cannot load http://my-api.rs.af.cm/api/products. Origin http://jsbin.com is not allowed by Access-Control-Allow-Origin.

I read all others answers on CORS and I don't want to use easyXDM.

4

2 回答 2

5

感谢 Ryan Olds 帮助我了解 CORS 请求的工作原理。

这里是正确的标题:

res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');

我所有的请求在他们的响应中都有那个标题。

我使用$.getJSONjQuery 进行 GET 请求,否则它不起作用。

您可以在此处查看示例:http: //jsbin.com/uwevuc/2/edit

http://jsbin.com/uwevuc/2

于 2012-07-31T09:02:34.353 回答
0

您还必须考虑您的预检请求。我建议您在项目中添加“cors”npm 包,并使用以下配置启动它:

const cors = require('cors');

app.use(cors({
    credentials: true,
    preflightContinue: true,
    methods: ['GET', 'POST', 'PUT', 'PATCH , 'DELETE', 'OPTIONS'],
    origin: true
});

这将为使用列出的方法的任何地址启用跨域请求。origin 参数非常灵活,您可以分隔一组地址,例如所有地址或通过正则表达式。这是包文档:

https://expressjs.com/en/resources/middleware/cors.html

于 2021-05-15T00:10:57.270 回答