前端怎么样用nginx代理解决跨域?

背景:之前的项目一直是实时上传到服务器,在服务器端 npm run dev;这样解决了跨域,但是因为要上传到服务器,没有在本地运行方便。
现在想解决一下。
之前的配置:
image.png

代码中 url 是统一管理的
image.png

现在要在本地启动 webpack 中的host 要改成 127.0.0.1;这样就会跨域,请求需要怎么配置 nginx 解决代理,或者使用其他方法解决跨域。
谢谢

阅读 2.4k
2 个回答

nginx:
在location下添加
add_header 'Access-Control-Allow-Origin' 'http://127.0.0.1:3000';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' '*';
add_header 'Access-Control-Allow-Headers' 'content-type,x-requested-with,token';

应用层解决:
php 使用中间件添加header

class Cors  
{  
    public function handle($request, Closure $next)  
    {  
        $allowOrigin = Request::header('origin');  
        $buffCorsConf = Config::get('buffge.cors');  
        if ( in_array($allowOrigin, $buffCorsConf['allow_origin_list'], true) ) {  
            header('Access-Control-Allow-Origin:' . $allowOrigin);  
            header('Access-Control-Allow-Methods:' . '*');  
            header('Access-Control-Allow-Headers:' . 'content-type,x-requested-with,token');  
            header('Access-Control-Allow-Credentials:' . 'true');  
        }  
        return $next($request);  
    }  
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题