折腾:
【已解决】reactjs中fetch调用接口出错:TypeError: Failed to fetch
期间,发现其实根本错误是:
js中POST调用访问服务器接口:
this.props.fetch(
url,
{
method : "POST",
headers : {
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify(postJson)
},
(data) => {
console.log("getUserDetail response: data=", data);
结果出错:
OPTIONS http://ip:port/xmt-web/getUserDetail.do 403 (Forbidden)
很是诡异。搞不懂为何出错。
js fetch OPTIONS 403 Forbidden
Receiving 403 Error on javascript fetch · Issue #340 · Yelp/yelp-fusion
fetch API cannot load error with cors in chrome/firefox · Issue #301 · github/fetch
换safari去访问同样url,结果出现类似的错误:
[Error] Failed to load resource: Preflight response is not successful (getUserDetail.do, line 0)
[Error] Fetch API cannot load http://ip:port/xmt-web/getUserDetail.do. Preflight response is not successful
http – Node.js CORS resulting in 403 Forbidden – Stack Overflow
Ajax request returns OPTIONS message 403 Forbidden
去服务器上运行试试
也是同样错误:
OPTIONS http://ip:port/xmt-web/getUserDetail.do 403 (Forbidden)
after Access-Control-Allow-Origin * still OPTIONS 403 Forbidden
ajax – Cross origin request with CORS filter – Stack Overflow
CORS preflight issues in Firefox and Chrome | Bonitasoft Community
CORS sync sends OPTIONS request instead of POST · Issue #2542 · jashkenas/backbone
Server-Side Access Control (CORS) – HTTP | MDN
Failed to load http://ip:port/xmt-web/getUserDetail.do: Response for preflight has invalid HTTP status code 403.
js fetch Failed to load Response for preflight has invalid HTTP status code 403
cors – Response for preflight has invalid HTTP status code 403 in Angular 5 – Stack Overflow
至此,还是很诡异的:
server端,可以正常通过Postman去POST:
POST http://ip:port/xmt-web/getUserDetail.do
Content-Type:application/json
body
JSON:
{
"accessToken": "c5xxx3a",
"clientId": "0a7xxxbd",
"sign": "1fxxx95"
}
正常返回json
{
"retCode": 0,
"retDesc": "success",
"data": {
…
返回的headers:
Access-Control-Allow-Headers →origin, Content-type, accept, x-requested-with, sid, mycustom, smuser
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin →*
Content-Disposition →inline;filename=f.txt
Content-Encoding →gzip
Content-Type →application/json;charset=UTF-8
Date →Tue, 26 Jun 2018 11:55:44 GMT
Server →Apache-Coyote/1.1
Transfer-Encoding →chunked
Vary →Accept-Encoding
而且Postman中测试OPTIONS,也是返回正常的200的:
Access-Control-Allow-Headers →origin, Content-type, accept, x-requested-with, sid, mycustom, smuser
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin →*
Allow →GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS
Content-Length →0
Date →Tue, 26 Jun 2018 13:11:25 GMT
Server →Apache-Coyote/1.1
但是js的fetch中,POST却出错:
OPTIONS http://ip:port/xmt-web/getUserDetail.do 403 (Forbidden)
Failed to load http://ip:port/xmt-web/getUserDetail.do: Response for preflight has invalid HTTP status code 403.
call path http://ip:port/xmt-web/getUserDetail.do -> res= {code: -9999, message: TypeError: Failed to fetch}
fetch path=getUserDetail.do with params={"method":"POST","mode":"cors","headers":{"Content-Type":"application/json","accept":"application/json"},"body":"{\"accessToken\":\"15xxx5cc\",\"clientId\":\"0axxxd\",\"sign\":\"0xxxb2\"}"} error code=-9999 message=TypeError: Failed to fetch, data=undefined
cors – Response for preflight has invalid HTTP status code 403 in Angular 5 – Stack Overflow
cors – Response for preflight has invalid HTTP status code 403 (Angular 4) – Stack Overflow
server support OPTIONS but js fetch 403 Forbidden
Support CORS enabled servers and OPTIONS requests · Issue #14 · graphql/express-graphql
http – Why is an OPTIONS request sent and can I disable it? – Stack Overflow
js POST OPTIONS 403
express – Node.js : POST – Request Method: OPTIONS Status Code: 403 Forbidden – Stack Overflow
ajax – Response for preflight 403 forbidden – Stack Overflow
http – Why is an OPTIONS request sent and can I disable it? – Stack Overflow
jquery ajax 请求中多出现一次OPTIONS请求及其解决办法_唐霜的博客
postman ok but js fetch OPTIONS 403
Solved: 403 Forbidden on POST method of /rest/api/2/issue …
Https POST works with postman but preflight fails on chrome browser – ionic-v1 – Ionic
关闭掉Chrome的CORS插件,但问题依旧:
实在不行,只能去考虑:
换成别的网络库,比如axios试试
➜ ucowsapp_h5_pure_web git:(pure_web) ✗ npm install –save axios
npm WARN [email protected] requires a peer of react-dom@^15.0.0 || ^16.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of react@^0.14.9 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of react-dom@^15.5.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of react-dom@^15.0.0 || ^16.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of react-dom@^15.5.x || ^16.x but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of react-dom@^15.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] No repository field.
npm WARN [email protected] No license field.
added 3 packages from 7 contributors and removed 9 packages in 13.992s
结果用:
let postJson = {
"accessToken": this.props.access_token,
"clientId": this.props.SSO.CLIENTID,
‘sign’: md5Sign
};
console.log("postJson=", postJson);
let stringifyPostJson = JSON.stringify(postJson);
console.log("stringifyPostJson=", stringifyPostJson);
url = "http://ip:port/xmt-web/getUserDetail.do";
axios({
method: ‘post’,
url,
headers: {
‘Content-Type’: ‘application/json’
},
data: stringifyPostJson
})
.then( (res) => {
console.log("axios: url=", url, ", res=", res);
})
.catch( (error) => {
console.error("axios: url=", url, ", error=", error);
});
出错:
xhr.js?1c58:178 OPTIONS http://ip:port/xmt-web/getUserDetail.do 403 (Forbidden)
dispatchXhrRequest @ xhr.js?1c58:178
xhrAdapter @ xhr.js?1c58:12
dispatchRequest @ dispatchRequest.js?71da:59
Promise.then (async)
request @ Axios.js?6523:51
wrap @ bind.js?46cd:9
getUserDetail @ index.js?b4b6:95
Main @ index.js?b4b6:50
createComponent @ component-recycler.js?d070:14
renderComponent @ component.js?4adf:108
renderComponent @ component.js?4adf:114
setComponentProps @ component.js?4adf:31
buildComponentFromVNode @ component.js?4adf:219
idiff @ diff.js?d966:87
innerDiffNode @ diff.js?d966:203
idiff @ diff.js?d966:125
innerDiffNode @ diff.js?d966:203
idiff @ diff.js?d966:125
diff @ diff.js?d966:28
renderComponent @ component.js?4adf:130
renderComponent @ component.js?4adf:114
renderComponent @ component.js?4adf:114
setComponentProps @ component.js?4adf:31
buildComponentFromVNode @ component.js?4adf:204
idiff @ diff.js?d966:87
diff @ diff.js?d966:28
render @ component.js?4adf:260
init @ index.js?1fdf:13
requestAnimationFrame (async)
(anonymous) @ index.js?1fdf:28
hotApply @ vendor.bundle_213ce55dc88d5e9648bc.js:594
hotUpdateDownloaded @ vendor.bundle_213ce55dc88d5e9648bc.js:312
hotAddUpdateChunk @ vendor.bundle_213ce55dc88d5e9648bc.js:292
webpackHotUpdateCallback @ vendor.bundle_213ce55dc88d5e9648bc.js:37
(anonymous) @ 0.213ce55dc88d5e9648bc.hot-update.js:1
localhost/:1 Failed to load http://ip:port/xmt-web/getUserDetail.do: Response for preflight has invalid HTTP status code 403.
index.js?b4b6:108 axios: url= http://ip:port/xmt-web/getUserDetail.do , error= Error: Network Error
at createError (eval at <anonymous> (main.bundle_213ce55dc88d5e9648bc.js:1200), <anonymous>:16:15)
at XMLHttpRequest.handleError (eval at <anonymous> (main.bundle_213ce55dc88d5e9648bc.js:1179), <anonymous>:87:14)
换成:
// data: stringifyPostJson
data: postJson
错误依旧。
axios Error: Network Error
Set a code/status for "Network Error" · Issue #383 · axios/axios
“It might be a Cors Error.”
HTTP post error: Error: Network Error · Issue #751 · axios/axios
Error: Network Error · Issue #1414 · axios/axios
javascript – React: Axios Network Error – Stack Overflow
node.js – Post request Axios : Network error – Stack Overflow
reactjs – Error: Network error on Axios API call – Stack Overflow
-》即:
换用axios去POST该api,还是同样错误:
OPTIONS http://ip:port/xmt-web/getUserDetail.do 403 (Forbidden)
axios Error: Network Error OPTIONS 403 Forbidden
axios OPTIONS 403 Forbidden
axios request blocked OPTIONS 403 Forbidden – Stack Overflow
“I use native js code it can upload image , i dont understand why axios cant?..”
java – axios 403 forbidden on OPTIONS request – Stack Overflow
javascript – How to configure CORS in a Spring Boot + Spring Security application? – Stack Overflow
关于vue 中的 axios 的post 请求命令 中的参数 – 开源中国社区
vue + axios发送post请求,403错误的解决 – 简书
使用Vue的axios vue-resource跨域不成功 但原生xhr就可以 – iftrue的回答 – SegmentFault 思否
总结感觉:
还是服务器端,没有完整的支持CORS
需要服务器去完整的支持CORS,应该就可以了。
【总结】
后来发现是:
是服务器端不支持CORS,在服务器端(java平台),加上对应代码:
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization,Content-type,Accept,X-Requested-With,sid,mycustom,smuser,Origin");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if ( httpRequest.getMethod().equals("OPTIONS") ) {
httpResponse.setStatus(HttpServletResponse.SC_OK);
return;
}
filterChain.doFilter(request, response);
后,无需移动端(js)中改动任何内容,即可解决此问题。
详见:
【已解决】reactjs中fetch调用接口出错:TypeError: Failed to fetch
转载请注明:在路上 » 【已解决】js中用fetch的POST访问服务器端接口出错:OPTIONS 403 Forbidden