Unable to fetch POST without no-cors in header

后端 未结 2 2097
执笔经年
执笔经年 2020-12-01 06:08

On making request like that:

return fetch(
            \'http://localhost:8000/login\',
            {   method: \'POST\',
                headers: new Header         


        
相关标签:
2条回答
  • 2020-12-01 06:46

    When using non-cors, all headers must be valid simple-headers. The only valid values for the content-type header that qualifies as a simple-header is:

    headers: [
      ['Content-Type', 'application/x-www-form-urlencoded'],
      ['Content-Type', 'multipart/form-data'],
      ['Content-Type', 'text/plain'],
    ]
    

    Exceptions with contingencies:

    headers: [
      ['Content-Type', 'application/csp-report'],
      ['Content-Type', 'application/expect-ct-report+json'],
      ['Content-Type', 'application/xss-auditor-report'],
      ['Content-Type', 'application/ocsp-request'],
    ]
    
    • simple-header
    • cors-protocol-exceptions
    0 讨论(0)
  • 2020-12-01 06:55

    The custom Content-Type header you're sending causes your request to be preflighted, which means an OPTIONS request, containing some metadata about the POST request that is about to be dispatched, will be sent before the actual POST request.

    Your server needs to be prepared to deal with this OPTIONS request. You haven't specified what the server is written in, but with express for example, you can register a middleware that intercepts all 'OPTIONS' requests, sets the Access-Control-Allow-Origin: * and Access-Control-Allow-Headers: Content-Type headers, and responds with 200.

    If it is possible for you to make the request using a 'Content-Type': 'text/plain' header, that would solve your problem. Alternatively you could use something that bypasses XHR entirely, like JSONP.

    0 讨论(0)
提交回复
热议问题