express + nginx 项目,代码上线后,单独访问接口是可以的,但是在前端项目中调接口的时候就报 405 ,有大哥知道这是怎么回事吗? nginx 配置如下:
server {
listen 80;
listen 443 ssl;
server_name xxx;
ssl_certificate /usr/local/nginx/conf/ssl/xxx.com.pem;
ssl_certificate_key /usr/local/nginx/conf/ssl/xxx.com.key;
ssl_protocols TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Method $request_method;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
}
前端项目配置了跨域,代码如下:
import { defineConfig } from "vite";
export default defineConfig({
...
server: {
open: true,
proxy: {
"/api": {
target: nginx 中配置的 server_name ,
changeOrigin: true,
},
},
},
...
});
请各位大哥指点一下
1
longgediyi999 2023-03-10 10:41:52 +08:00
Nginx
location /api { proxy_pass http://127.0.0.1:3000; } 重启项目和 Nginx 试试 |
2
qingshui33 OP @longgediyi999 刚刚试了下,不行
|
3
qingshui33 OP 补充一下,前端 nginx 的配置如下:
server { listen 80; listen 443 ssl; server_name aaa.com; root /data/wwwroot/xs-blog/dist; index index.html; ssl_certificate /usr/local/nginx/conf/ssl/aaa.com.pem; ssl_certificate_key /usr/local/nginx/conf/ssl/aaa.com.key; location / { try_files $uri $uri/ /index.html; } } |
4
yaphets666 2023-03-10 11:18:41 +08:00
单独访问接口是用 postman 吗
|
5
qingshui33 OP @yaphets666 是的
|
6
qingshui33 OP @yaphets666 在本地的前端项目里面也可以调通
|
7
yaphets666 2023-03-10 11:38:12 +08:00
@qingshui33 前端这个跨域你 build 之后不起作用的,server 这个对象里的东西只在本地有用。你把你前端请求的 url 发出来看看,然后再检查下前端项目部署的位置,是不是 nginx 中 html 目录下,而不是 html/xxx/xxx 目录
|
8
qingshui33 OP @yaphets666 嗯嗯,好的,我看看啊
|