前后端跨域解决方案

76 阅读1分钟

1.在开发过程中,vue框架下proxy可解决此问题

2.生产环境中

2.1.后端可使用cors中间件

2.2.nginx配置:

允许跨域的请求,设置为具体的来源

    add_header 'Access-Control-Allow-Origin' *;
    # 允许携带cookie请求
    # add_header 'Access-Control-Allow-Credentials' 'true';
    # 允许跨域请求的方法:GET, POST, OPTIONS, PUT
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT';
    # 明确允许的请求头部信息
    add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With, token, sec-ch-ua, sec-ch-ua-mobile, sec-ch-ua-platform';
    # 允许发送按段获取资源的请求
    add_header 'Access-Control-Expose-Headers' 'Content-Length, Content-Range';

    # 处理OPTIONS预检请求
    if ($request_method = OPTIONS) {
        add_header 'Access-Control-Allow-Origin' *;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With, token, sec-ch-ua, sec-ch-ua-mobile, sec-ch-ua-platform';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Length' 0;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        return 204;
    }