Session failure problem when JavaScript fetch cross-domain request

Source: Internet
Author: User
Tags php server

JavaScript uses fetch to cross-domain requests by default without a cookie, which can cause the session to expire.

Fetch (URL, {    ' POST ',    ' include ',    headers: {      ' content-type ': ' Application/x-www-form-urlencoded ',    },    body:JSON.stringify ({      data:options.data    })  } )
Credentials: ' Include ' can be a fetch with cookies. But the problem comes.
Originally set header on server side (PHP server)
    Header ("Access-control-allow-origin: *");

Will error:

A Wildcard ' * ' cannot be used in the ' Access-control-allow-origin ' header when the credentials flag is true. Origin ' http://localhost:8000 ' is therefore not allowed access.

You can see that the ' * ' is not allowed, then it is changed to access the domain name (here is the local call so it is http://localhost:8000)

Header ("access-control-allow-origin:http://localhost:8000");

After the change to send the request again, or error

Credentials flag is ' true ' and the ' access-control-allow-credentials ' header is '. It must is ' true ' to allow credentials. Origin ' http://localhost:8000 ' is therefore not allowed access.

Say ' access-control-allow-credentials head must be true, then continue to increase

Header ("Access-control-allow-credentials:true");

After the addition of the normal access, and the session is also available.

Ps:fetch There is a mode is no-cors, found after the return of the status is 0, after checking the information

no-corsMode is only to CDN content, such as scripts, CSS and image, you cannot be used for getting data, was right response.status = 0 behavior

No-cors mode can only be used to get CDN content, such as scripts, CSS files and pictures, if used to get data such as JSON format will return status=0

Session failure problem when JavaScript fetch cross-domain request

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.