使用nginx部署前后端分离项目,处理跨域问题(共享cookie)

     1.唠嗑

 踩坑了,花费一天时间,开始对nginx配置不懂,老是弄错了配置文件,之前装的nginx ,cofnig有两个,nginx.config和nginx.config.def  ,开始配置我在nginx.config中配置的,后面一直在改def,我说怎么把配置的前端地址删掉还能访问,气得我把nginx删掉了。

后面我又找了一个安装教程,很不错(1条消息) CentOs7安装nginx【详细】_centos7 配置nginx_小二,,来杯咖啡的博客-CSDN博客icon-default.png?t=N6B9https://blog.csdn.net/qq_45316925/article/details/128957728

 按照这个教程装,我也踩坑了,我部署项目的时候,一直在nginx.1.21里面配置conf

发现把前端放入到nginx/nginx1.21/html里面报错,我放到了nginx/html里面,一直访问不了页面

后面无意中发现nginx/conf中还有config文件,原来这个才是真正的配置文件,nginx.1.21目录只是告诉安装的版本。废话不多说,后端坑多,前端正常调就好了。

2.后端跨域配置。

package com.zuodou.cors;

import org.codehaus.plexus.component.annotations.Component;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws
            IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        httpResponse.setHeader("Access-Control-Allow-Origin", "服务器的nginx配置的端口");
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        httpResponse.setHeader("Access-Control-Allow-Headers", "*");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");

        chain.doFilter(httpRequest, httpResponse);
    }
}

3.这个是配合jwt使用的拦截器,我原本就写的后面这点,发现走了代理就调不到接口了。

 建议全局设置

 4.上nginx配置》》》》》》》》

  server {
        listen                             8080;
        server_name                        127.0.0.1;
        #解决Router(mode: 'history')模式下,刷新路由地址不能找到页面的问题
       location / {
               root   html/zuodou/dist/;  #我放前端的目录
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
    
        location ^~ /zuodou {   #这个zuodou的意思就是只要前端调用zuodou后缀的接口都会转发到2380
            proxy_pass              http://127.0.0.1:2380;  #后端接口的地址
            proxy_set_header        Host 127.0.0.1;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    }
        
    }

最后设置一下系统服务

vim /lib/systemd/system/nginx.service

[Unit]
Description=nginx service
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target
 

配置完成把nginx停掉

systemctl daemon-reload

systemctl start nginx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值