Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

reactjs - Using fetch API with mode: 'no-cors', can’t set request headers

I am trying to hit a service end point and the service is a login service I am using the authentication type as basic ,The code is in react and using the fetch library however even if i set the headers field in my request I am unable to see the values of corresponding headers in my request in network tab?

Following is the code :

var obj = {
  method: 'GET' ,
  mode : 'no-cors',
  headers: {
      'Access-Control-Request-Headers': 'Authorization',
      'Authorization': 'Basic amFzcGVyYWRtaW46amFzcGVyYWRtaW4=',
      'Content-Type': 'application/json',
      'Origin': ''
  },
  credentials: 'include'
};
fetch('http://myreport:8082/jasperserver/rest/login/', obj ).then(…

Popup where its asking me for username and password Popup where its asking me for username and password


Request and response calls from the network tabs Request and response calls from the network tabs

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

None of your headers are CORS-safelisted, so they can not be attached to the request.

Explanation:

  1. no-cors request mode sets guard property for a headers object to request-no-cors
  2. To append a name/value (name/value) pair to a Headers object (headers), browser have to run these steps:

    1. Normalize value.

    2. If name is not a name or value is not a value, then throw a TypeError.

    3. If guard is "immutable", then throw a TypeError.

    4. Otherwise, if guard is "request" and name is a forbidden header name, return.

    5. Otherwise, if guard is "request-no-cors" and name/value is not a CORS-safelisted request-header, return. ← your scenario

    6. Otherwise, if guard is "response" and name is a forbidden response-header name, return.

    7. Append name/value to header list.

  3. CORS-safelisted request-header (case-insensitive):
    • Accept
    • Accept-Language
    • Content-Language
    • Content-Type, but only if the value is one of:
      • application/x-www-form-urlencoded
      • multipart/form-data
      • text/plain

You can learn more about fetch's Headers class specs here: https://fetch.spec.whatwg.org/#headers-class


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...