使用CPP实现了后端http服务器,但是在和前端联调时发现无法正常使用,前端反馈遇到了跨域的问题。
百度跨域的相关概念之后,了解不少CORS的知识,总结一下就是前端发来的http请求封装了一层,原始的http请求被处理成了OPTIONS方法的请求,真实的请求方法藏在了Access-Control-Request-Method字段中。
但是目前实现的孱弱的http服务器只能处理直白的GET,POST请求,所以查找相关资料之后,知道nginx可以处理跨域的问题。
开始学习nginx的相关知识,了解到nginx主要是配置文件配好即可,折腾了一下午之后,终于弄通了,现把成果记录下来。
server{
listen 8000;
location /api/{
#处理OPTIONS的请求
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS always;
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,x-auth-token always;
add_header Access-Control-Max-Age 1728000 always;
return 204;
}
if ($request_method = 'POST') {
proxy_pass http://127.0.0.1:8088;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' '*';
}
if ($request_method = 'GET') {
#正常请求转发到服务端口
proxy_pass http://127.0.0.1:8088;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' '*';
}
}
}