如何解决出现AXIOS的Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

问题描述:

由于restful接口需要在头部header传递两个字段:

Content-Type: application/json
Access-Token: 84c6635800b14e0eba4f7ece65e095a1

但是,在vue.js里面配置:

执行发送的时候出现:

意思是预发请求的时候不通过,不再正式发请求

经过反复的测试,发现,header里面包含自定义字段,浏览器是会先发一次options请求,如果请求通过,则继续发送正式的post请求,而如果不通过则返回以上错误

那这样就只能在服务端配置options的请求返回,代码如下:

 

  // TODO 支持跨域访问
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
        response.setHeader("Access-Control-Expose-Headers", "*");

        if (request.getMethod().equals("OPTIONS")) {
            HttpUtil.setResponse(response, HttpStatus.OK.value(), null);
            return;
        }

上面代码需要加入允许的头部,content-type和access-token,并且判断请求的方法是options的时候,返回ok(200)给客户端,这样才能继续发正式的post请求。

修改之后成功发了post请求。

PS:

看了网上这么多解释,基本都用不到,关于AXIOS自定义头部字段的问题,貌似只有上述方法能够解决

 

GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:3 个月前 )
2134cb94 * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance * fix ci_static_analysis_clang (ci_clang_tidy) * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance 8 天前
6057b31d * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * Use ubuntu-latest image to run Valgrind (#4575) * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Ubuntu image to run valgrind * Use Clang image to run iwyu (#4574) * :wrench: use Clang image to run iwyu * :wrench: use Clang image to run iwyu * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :art: format code * :hammer: clean up 9 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐