golang-Cookie cross-domain settings in gin (with Ajax)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

1. When I use cookies in Golang, in the case of separation between the front and back ends, the cross-domain is not allowed. The code is as follows:

Func accessjsmiddleware () gin. Handlerfunc {   return func (c *gin. Context) {      W: = C.writer      //Handle Js-ajax cross-domain Problem      w.header (). Set ("Access-control-allow-origin", "*")//allows access to all domain      w.header (). Set ("Access-control-allow-methods", "Options, POST")      W.header (). ADD ("Access-control-allow-headers", "Content-type")      W.header (). ADD ("Access-control-allow-headers", "Access-token")      C.next ()   }}

1.1. This adds a cross-domain middleware at the start of the program, using the following

API: = Rounter. Group ("/api") API. Use (Accessjsmiddleware ())

The above settings are denied when Ajax requests to use cookies

2. Then I made a modification to solve the problem

2.1.ajax request to add a setting

Xhrfields: {withcredentials:true},

2.2. Then modified the settings for cross-domain middleware

Func accessjsmiddleware () gin. Handlerfunc {return func (c *gin. Context) {w: = c.writerr:=c.request//handles Js-ajax cross-domain problem W. Header (). Set ("Access-control-allow-credentials", "true") W.header (). Set ("Access-control-allow-origin", R.header.get ("Origin")) W.header (). Set ("Access-control-allow-methods", "Options, POST") W.header (). ADD ("Access-control-allow-headers", "Content-type") W.header (). ADD ("Access-control-allow-headers", "Access-token") C.next ()}}

The above solved the problem of cross-domain cookie, feel useful on the point of a recommendation and attention, after all, I am also a shy ⁄ (⁄⁄ ⁄ω⁄ ⁄⁄) ⁄ small public who.

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.