nginx实现跨域详细教程,附带前后端实例
去官网下载nginx
为了方便启动和关闭nginx,按照如图新建start.bat,stop.bat文件,双击即可在windows下启动、关闭nginx
start.bat代码:
start nginx
echo success
pause
stop.bat代码
nginx.exe -s stop
echo success
pause
当然为了方便,也可以新建一个isRun.bat;来检查是否启动成功
isRun.bat代码
tasklist /fi "imagename eq nginx.exe"
echo "isRun?"
pause
看到上图就是启动成功,没有就是失败,看logs/error.log,查看错误信息,百度一下。
注意文件夹不能有中文。
配置目录:nginx-1.14.1\conf\nginx.conf
主要配置:
server {
# nginx监听的端口
listen 1999;
# 前端项目ip,可以localhost
server_name 172.30.34.180;
#charset koi8-r;
#access_log logs/host.access.log main;
# 前端项目的端口
location / {
proxy_pass http://172.30.34.180:8080/;
}
# 服务端的ip端口
location /myServer {
proxy_pass http://172.30.34.180:3000/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
测试代码前端代码:
/* eslint-disable */
<template>
<div>
<button @click="test">测试</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
test () {
axios.get('/myServer').then(res => {
console.log(res)
})
}
}
}
</script>
测试后端nodejs代码片段:
var fn_index = async (ctx, next) => {
console.log(html)
ctx.response.body = {
state: 200,
data: {
list: [{ userName: "张三", id: 3 }, { userName: "李四", id: 4 }]
}
};
console.log(ctx.response)
};
服务端端口3000
效果图:
注意:一定要用nginx listen的端口
成功跨域!
提示:上线时需要把nginx一并上线,根据具体的服务器配置