使用Fetch连接前后端时服务器抛415错误,URL拼接异常求助
问题与解决记录
遇到的问题
- 前端通过Fetch提交注册表单时,服务器返回415错误,IntelliJ提示
Content type 'text/plain;charset=UTF-8' not supported - Postman测试后端接口
http://127.0.0.1:8080/registration正常,但前端控制台显示请求URL被拼接为http://127.0.0.1:5501/127.0.0.1:8080/registration,返回405 Method Not Allowed
前端代码
"use strict"; ///////////////////////////////////////////////// // Data let inputSignUpFirstName = document.querySelector(".signUp__input--firstName"); let inputSignUpLastName = document.querySelector(".signUp__input--lastName"); let inputSignUpPhoneNumber = document.querySelector(".signUp__input--phoneNumber"); let inputSignUpPin = document.querySelector(".signUp__input--pin"); const btnSignUp = document.querySelector(".signUp__btn"); const formSignUp = document.querySelector(".signUp"); ///////////////////////////////////////////////// // EventListeners formSignUp.addEventListener("submit", addUser); ///////////////////////////////////////////////// // Functions function addUser(e){ e.preventDefault(); fetch("http://127.0.0.1:8080/registration", { method: "POST", headers: { Accept: "application/json, text/plain;charset=UTF-8", "Content-Type": "application/json", }, mode: "no-cors", body: JSON.stringify({ firstName: inputSignUpFirstName.value, lastName: inputSignUpLastName.value, telephoneNumber: inputSignUpPhoneNumber.value, password: inputSignUpPin.value, }), }) .then((response) => { console.log(response); return response.json(); }) .then((data) => console.log(data)) .catch((error) => console.log(error)); }
问题分析
- 415错误原因:代码中设置了
mode: "no-cors",该模式下浏览器会强制将请求的Content-Type改为text/plain,而后端接口只接受application/json格式,因此触发不支持媒体类型的错误。 - URL拼接错误与405:
no-cors模式会导致浏览器对请求做特殊处理,引发URL解析异常;同时跨域配置缺失,后端拒绝了前端的跨域请求,返回405。
解决方案
- 移除
mode: "no-cors":该模式会限制请求头的正常设置,移除后浏览器才能正确发送Content-Type: application/json请求头。 - 配置后端CORS:在后端(IntelliJ中)添加CORS配置,允许前端源
http://127.0.0.1:5501的跨域请求,同时允许POST方法和application/json的请求内容类型。 - 修正请求头认知:前端不需要在请求头中添加
Access-Control-Allow-Origin,这个是后端需要返回的响应头,用于告知浏览器允许跨域。
最终解决结果
通过配置后端CORS并移除mode: "no-cors",问题已解决,前端可正常通过Fetch提交JSON格式数据到后端接口。
内容的提问来源于stack exchange,提问作者Tati K
相关产品推荐
相关产品推荐

