跨域资源共享 CORS

概述

如果需要在前端与不同域的后端进行通信,可以在后端配置CORS,允许指定的域名访问后端资源。

开始

通过配置合适的响应头,可以明确指定允许的来源域、请求方法和头部信息。

Node.js

app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  res.header("Access-Control-Allow-Credentials", "true");
  next();
});

Nginx

server {
    listen 80;
    server_name localhost; #你的域名
    root html;
    index index.html index.htm;

    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Credentials "true";
    add_header Access-Control-Allow-Methods "PUT,POST,GET,DELETE,OPTIONS";
    add_header Access-Control-Allow-Headers "token,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,XRequested-With";

    location / {
        proxy_pass http://localhost:3000; #你的代理服务
    }
}
posted @ 2023-06-03 18:36  摸鱼的云小逸  阅读(14)  评论(0编辑  收藏  举报