nginx解决前端请求接口出现跨域的问题
dearweb
发布:2021-08-21 15:05:41阅读:
之前给大家分享过vue.config.js来处理vue前端开发时的跨域问题,今天带来的是服务端nginx处理前端请求时的跨域问题。
首先去官网下载安装nginx
前往官网下载nginx
首先给大家说一下options请求正确的访问
下载完之后配置nginx里面的nginx.conf文件
#user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
# 监听端口
listen 8000;
server_name localhost;
location = /50x.html {
root html;
}
# 包含路由
location /userInfo/login {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Max-Age 1728000;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header Content-Type' 'text/plain; charset=utf-8';
add_header Content-Length 0 ;
#return 204;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 实际请求地址
proxy_pass http://192.168.4.9:8091/userInfo/login;
}
}
}直接点击nginx.exe启动nginx

然后再去执行本地请求就可以了。
文件配置的含义解释
if ($request_method = 'OPTIONS') {...} 当请求方法为 OPTIONS 时:
1)添加允许源 Access-Control-Allow-Origin 为 * (可根据业务需要更改)
2)添加缓存时长 Access-Control-Max-Age,当下次请求时,无需再发送 OPTIONS 请求
3)添加允许的方法,允许的首部
4)添加一个内容长度为0,类型为 text/plain; charset=utf-8 , 返回状态码为 204 的首部,正常发送请求,不需要使用return
至此,完成 OPTIONS 请求的正确响应
下面是跨域请求正确的访问
location /example {
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Max-Age 1728000;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header Content-Type' 'text/plain; charset=utf-8';
add_header Content-Length 0 ;
return 204;
}
if ($http_origin ~* (https?://(.+\.)?(example\.com$))) {
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
add_header Access-Control-Expose-Headers Content-Length,Content-Range;
}
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080/;
}文件配置的含义
if ($http_origin ~* (https?://(.+\.)?(example\.com$))) {...}, 当 origin 为合法域名(可根据业务调整或去除合法域名验证)时:
1)添加允许源Access-Control-Allow-Origin为 $http_origin (可根据业务需要更改)
2)添加允许认证Access-Control-Allow-Credentials为 true ,允许接收客户端 Cookie(可根据业务需要更改。
3)当设置为true时,Access-Control-Allow-Origin 不允许设置为 *) 添加允许的方法,暴露的首部
至此跨域的问题可以得到基本解决,你学会了吗?当然还有一种你在进行vue开发时也可以采用 webpack-dev-server 的 proxy 选项来快速解决跨域问题,我在之前的文章中有写到,可以去看看vue.config.js。
// vue.congf.jsmodule.exports = { //...
devServer: {
proxy: { '/api': {
target: 'http://localhost:3000',
pathRewrite: {'^/api' : ''}
}
}
}
} 小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧