鍍金池/ 問答/Linux  HTML/ react 項目 nginx配置問題

react 項目 nginx配置問題

在使用nginx 配置前后端分離項目的時候出現了一個問題,前端是用react做的,路由用的是history模式的。 nginx配置如下:

server {
    listen    8000;
    server_name   test;
    charset utf-8,gbk;
    location / {
        root /opt/web/test1;
        #index index.html index.htm;
        try_files $uri /index.html;
    }

    location /v1/ {
        proxy_pass http://127.0.0.1:8001/xxx/v1/;
    }
}

在配置之后可以訪問到前端頁面,但是ajax請求中的路徑會多出一級目錄,規(guī)則如下:

//url路徑
http://localhost:3000/bill/query 
// 請求路徑就會多出一個 /bill 如下:
http://localhost:3000/bill/v1/xxx/xxx/list 
// 我希望的請求路徑是
http://localhost:3000/v1/xxx/xxx/list 

同理 如果我的url地址是 http://localhost:3000/test/query ,請求的路徑就會變成http://localhost:3000/test/xxx/xxx/list.

當我把react中的路由變成hash模式的時候請求就沒問題了,也就是將nginx配置中的 try_files $uri /index.html;去掉。
哪位大佬知道原因嗎,萬分感謝?。

回答
編輯回答
互擼娃

原因是你在項目中配置url的時候寫成相對路徑了。
應該在url前加一個 /,如下:

fetch('/vi/xxx/xxx/list');
2017年11月22日 00:31
編輯回答
尐飯團

打包的時候,配置一下publicPath

2018年4月18日 13:29