Nodejs setting cookies across domains

Source: Internet
Author: User

Do the project in the Vue family bucket +express. Want to do a free landing function, select the session program. After the server Setup session, the response headers returned are Set-cookie, but the browser's application cookies are missing SessionID cookies that are not returned. It took a long time to realize that this was a cross-domain cause problem. The front end is 8080 ports and the back end is 4000 ports. By default, cross-domain request browsers do not carry credential information (cookies, SSL certificates, etc.), and server-set cookies are blocked by the browser

So the solution is

The frontend of the Ajax latter Axios needs to be set Withcredentials to true. Mine is Axios, so the request will carry a cookie.

At the same time, the backend uses cors middleware. Can

// need to install and introduce middleware corsconst Cors = require (' cors '); var corsoptions = {  ' http://localhost:8080 ',  true,  ' 1728000 '  // This is for }app.use (Cors (corsoptions))   specifically set across domains Set up cross-domain

If you do not use middleware, you can do so, the settings displayed

Access-control-allow-credentials is True

Note Origin cannot be an * number. This way, the browser will not intercept the cookie set by the server.

1App.all (' * ',function(req, res, next) {2Res.header ("Access-control-allow-origin", Req.headers.origin);//need to display the settings source3Res.header ("Access-control-allow-headers", "Origin, X-requested-with, Content-type, Accept");4Res.header ("Access-control-allow-methods", "Put,post,get,delete,options");5Res.header ("Access-control-allow-credentials",true);//with Cookies7Res.header ("Content-type", "Application/json;charset=utf-8");8 next ();9});

Nodejs setting cookies across domains

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.