前端調用接口的時候跨域了怎么辦呢,如下代碼跨域:
$.ajax({
type:'POST',
data:{accountPwd: "loveyou",accountUser: "loveme"},
url:'http://192.168.1.99:3309/mice/login',
success:function(res){
console.log(res)
}
})
image.png
通過nginx反向代理
下載nginx:http://nginx.org/en/download.html
解壓到后的目錄如下:
image.png
配置:conf/nxinx.conf
nginx.conf默認的配置最好不要改,我們在nxinx.conf同目錄下新建一個配置文件myconfig.conf并添加如下代碼:
server {
listen 5328; #監(jiān)聽端口 可以訪問127.0.0.1:8090
server_name localhost; #這里要是使用需要配本地的host
#charset koi8-r;
access_log logs/k8s.log;
location / {
root E:/MyProject/demo/iframe/a; #你項目的根目錄
index index.html index.htm;
}
location /mice {
proxy_pass http://192.168.1.99:3309; #這里填上服務器地址
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
在nginx.conf中引用(在http{}里面server {}外面),如下:
http {
...
include myconf.conf;
server {
...
}
...
}
將js代碼url替換成下面的 url:'/mice/login',
$.ajax({
type:'POST',
data:{accountPwd: "loveyou",accountUser: "loveme"},
url:'/mice/login',
success:function(res){
console.log(res)
}
})
cd到nginx.exe目錄下命令行s輸入tart nginx.exe運行;
運行后,訪問localhost:5328,這時候就可以看到E:/MyProject/demo/iframe/a下的頁面;
此時就可以看到請求的數據啦;
image.png