axios的put请求设置'Content-Type': 'application/json'无效的问题
·
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
restful风格接口在使用put请求的时候设置headers: {'Content-Type': 'application/json'}请求无效,并且出现Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.报错
在网上找了很多文章都没有效果,结果仔细想了一下是因为Content-Type没有被服务端允许跨域访问,而且请求接口的时候会先发出OPTIONS预检测,服务端收到OPTIONS之后要做出回应,否则前端无法发起正是请求,
解决方案:
第一步、允许跨域 Header
//跨域
hresp.setHeader("Access-Control-Allow-Origin", "*");
//跨域 Header
hresp.setHeader("Access-Control-Allow-Methods", "*");
hresp.setHeader("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE");
第二步、后端响应OPTIONS
if (request.getMethod().equals("OPTIONS")) {
HttpUtil.setResponse(response, HttpStatus.OK.value(), null);
return;
}
这样解决可以啦~
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)