我正在托管一个nodejs服务器,以及一个通过nginx的单独网站。该网站通过html5 fetch
与服务器进行通信。
在服务器上,我有/api.profile
的路由,允许用户获取PATCH信息。使用Postman进行测试,一切正常,但是当尝试从网站发送PATCH请求时,我收到以下错误:
fetch API无法加载http://192.168.0.205:3000/api.profile。在预检响应中,Access-Control-Allow-Methods不允许使用方法补丁。
这让我相信它是fetch API或nginx问题。我在线尝试了多篇文章和配置,但是我无法解决这个问题 以下是我的nginx配置的转储,以尝试允许CORS以及vue-router的html5历史模式。
user developer staff;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
error_log /Library/Logs/nginx/error.log;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
# st login: Mon Jun 19 11:43:00 on ttys003
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80 default_server;
listen [::]:80 default_server;
root /Users/Developer/Desktop/Work/mentorconnect_client/web;
index index.html;
server_name localhost;
location / {
try_files $uri $uri/ @rewrites;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Origin,Accept';
if ($request_method = 'OPTIONS') {
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'PATCH') {
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
}
location @rewrites {
rewrite ^(.+)$ /index.html last;
}
location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
# Some basic cache-control for static files to be sent to the browser
expires max;
add_header Pragma public;
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}
}
}
在服务器上,在app.js
中,我有以下内容来启用CORS:
let corsOptions = {
origin: (origin, next) => {
next(null, true)
},
optionsSuccessStatus: 200,
credentials: true,
preflightContinue: true,
methods: ['GET', 'POST', 'PATCH', 'OPTIONS']
}
app.use(cors(corsOptions))
使用cors设置配置文件路由(global.cors是使用配置的cors实例):
app.options('/api.profile', global.cors)
app.patch('/api.profile', global.cors, (req, res) => {