美文网首页
怎么使用反向代理服务器Nginx解决跨域问题

怎么使用反向代理服务器Nginx解决跨域问题

作者: 小m_up | 来源:发表于2017-07-28 15:12 被阅读344次

近期在写一个项目,是前后端分离的,但是因为项目还在初期阶段,所以并没有部署到服务器上,那么我使用Ajax访问别人的接口的时候就出现了跨域问题:
代码:

$.ajax({
        url: "http://10.10.2.254:8080/firmware/firmware/getfirmwaretree/596701ad35bd191130442039",
        type: "get",
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        xhrFields: {withCredentials: true},
        success: function (res) {
            console.log(res);
       }
});

此时出现了下面的错误:



此时就想到了使用反向代理服务器Nginx,因为是我写前端,所以为了自己测试方便,就在自己的电脑上装,这样以后要部署到服务器也比较方便,那么我们就开始怎么搞吧

步骤

  • 安装Nginx
sudo apt-get update
sudo apt-get install nginx
  • 写配置文件
vim server.for.test

写入下面代码:

server {

    server_name_in_redirect off;

    location / {
        # 将下面的模板改为修改为你的项目地址
        # alias /path/to/your/project/; 
        alias /home/myProject/firmwareDepthAnalysisAndDetection/; //这是我的地址

    }
    location /api {
        rewrite /api/(.+)$ /$1 break;
        proxy_pass http://10.10.2.254:8080; //这里写自己要访问的接口api
    } 
}

然后执行下面命令:

sudo cp server.for.test /etc/nginx/sites-available
cd /etc/nginx/sites-enabled 
sudo ln -s /etc/nginx/sites-available/server.for.test
ls  //查看该文件夹下有没有其他文件,如果有则删除,没有则继续
sudo nginx -t 
sudo nginx -s reload

那么我们已经完成了Nginx的配置,接下来看是否完成:

curl localhost index.html

如果显示了你的代码,说明配置Nginx成功完成

  • 修改请求api
    修改我们的Ajax请求api为:
$.ajax({
        url: "/api/firmware/firmware/getfirmwaretree/596701ad35bd191130442039",
        type: "get",
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        xhrFields: {withCredentials: true},
        success: function (res) {
            console.log(res);
       }
});

此时打开的浏览器,输入http://localhost/index.html,就会出现你的页面哦,你所要的数据也获取到啦!

相关文章

网友评论

      本文标题:怎么使用反向代理服务器Nginx解决跨域问题

      本文链接:https://www.haomeiwen.com/subject/etzxlxtx.html