跨域问题的出现是因为浏览器的同源策略问题,所谓同源:就是两个页面具有相同的协议(protocol),主机(host)和端口号(port),它是浏览器最核心也是最基本的功能,如果没有同源策略我们的浏览器将会十分的不安全,随时都可能受到攻击。
在vue开发中实现跨域:在vue项目根目录下找到vue.config.js文件(如果没有该文件则自己创建),在proxyTable中设置跨域
代码:
proxyTable: {
'/api': {
target: 'http://127.0.0.1:888', // 接口域名
// secure: false, // 如果是https接口,需要配置这个参数
changeOrigin: true, //是否跨域
pathRewrite: {
'^/api': '' //需要rewrite的,
}
}
},
还可以使用nginx代理
先去下载一个nginx,然后去配置nginx.conf文件
nginx.conf文件
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
client_max_body_size 8M;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 100;
proxy_read_timeout 10000;
#gzip on;
server {
listen 8080; #监听端口
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://localhost:8001;
proxy_redirect default ;
}
location /api/ {
proxy_pass http://localhost:8000;
proxy_redirect default ;
}
# 静态页面目录
# root E:\asn\crm_web;
# 默认首页
# index login.html;
# location / {
# 用户浏览器端的缓存设置
# location ~* \.(css|js|jpg|jpeg|gif|png|swf|htm|html|json|xml|svg|woff|ttf|eot|map|ico|woff2)$ {
#expires 1h;
# if (-f $request_filename) {
break;
# }
# }
# 动态页面,交给tomcat处理
# if ( !-e $request_filename) {
# proxy_pass http://127.0.0.1:8088;
# }
# }
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
}
如图
红色标注,上面一个是静态文件服务,下面一个是接口服务