nginx解决vue项目开发跨域问题

1、为了模拟跨域的开发情况,本地可以起一个后台服务

const http = require('http');

const PORT = 3200;

// 创建一个 http 服务
const server = http.createServer((request, response) => {
  response.end("hello world");
});

// 启动服务, 监听端口
server.listen(PORT, () => {
  console.log('服务启动成功, 正在监听: ', PORT);
});

这样就启动了一个后台服务,端口3200

2、修改host文件

路径:C:\Windows\System32\drivers\etc\hosts

最后一行添加

127.0.0.1 localhost

y意思访问 localhost 的时候, 直接指向我们本机.

 3.修改nginx.conf配置文件

	server {
		listen 8200;
		server_name localhost;
        # 监听8200下的根目录
		location / {
            # 把请求进行转发
			proxy_pass http://127.0.0.1:8081;

		}
		# 监听根目录下的 /api 路径
		location /api/ {
			# 把请求进行转发
			proxy_pass http://127.0.0.1:3200;
		}
	}

 ps:我本地的前端项目是8081端口,根据实际情况来

双击nginx.exe启动nginx

4.打开页面

浏览器打开http://192.168.1.112:8200/,成功访问接口

nginx解决vue项目开发跨域问题_第1张图片

有个坑就是修改nginx.conf文件后直接在nginx的根目录打开cmd,执行

nginx -s reload

不要再次双击 nginx.exe,可以打开任务管理器进行排查

你可能感兴趣的:(vue.js,nginx,javascript)