Error message: The requested resource in Golang does not have an 'Access-Control-Allow-Origin' header present, which means that the origin 'null' is not permitted to access it

I am currently experimenting with checking if a domain A client can send a domain B cookie to domain B.

Here is the Go code I am using:

package main

import (
    "fmt"
    "net/http"
    "log"
    "time"
    "encoding/json"
)

func setCookie(w http.ResponseWriter, r *http.Request) {
    expiration := time.Now().Add(365 * 24 * time.Hour)
    cookie := http.Cookie{Path: "/test_receive_cookie", Name: "test_cors", Value: "test_cors", Expires: expiration}
    http.SetCookie(w, &cookie)
    fmt.Fprintf(w, "Success")
}

func receiveCookie(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.Cookies())

    data := make(map[string]interface{})
    for _, cookie := range r.Cookies() {
        data[cookie.Name] = cookie.Value
    }
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(data)
}

func main() {
    http.HandleFunc("/set_cookie", setCookie)
    http.HandleFunc("/test_receive_cookie", receiveCookie)
    err := http.ListenAndServe(":8012", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

To initiate the process, I first access http://localhost:8012/set_cookie, then I open an HTML file containing JavaScript that uses this library.

        this._xhr.get(
            "http://localhost:8012/test_receive_cookie", 
            { headers: { "Access-Control-Allow-Origin": "*" }},
            function(err, resp) {
                console.log(resp);
                console.log(err);
            });

The following outcomes were observed:

  1. Browser returns

Failed to load http://localhost:8012/test_receive_cookie: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

  1. My server prints [] from fmt.Println(r.Cookies())

  2. If I directly access

    http://localhost:8012/test_receive_cookie
    , I can see the previously set cookie displayed in the browser. However, when I open an HTML page calling that endpoint, the server receives an empty cookie.

My question is how can I successfully pass the cookie back to

http://localhost:8012/test_receive_cookie
through client-side code?

Could there be some configuration settings missing in my code?

Answer №1

To resolve the issue, make sure your Go server is sending the necessary Access-Control-Allow-Origin headers. The client cannot generate these headers on its own (refer to CORS). By updating your server to include this header, you can prevent errors from occurring on the client side.

Here's an example:


w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")

For more information, check out:

How to Enable CORS in Golang

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Timing feature utilized in a Web Application

My latest project involves developing a web-based testing application using CakePHP. Here's how it works: when a user starts a test, the exact start time is stored on the web server. Once the test is completed and the answers are submitted, the serve ...

What is the best way to attach a single block of Javascript code to different div elements without executing them simultaneously?

Running a small ecommerce shop, I have designed product cards using HTML, CSS, and a bit of Jquery for animations. However, a problem arises when clicking the "add to cart" button on any product card as it adds all items to the cart and triggers animations ...

Unable to navigate through select2 dropdown if fixed div is present

I am facing an issue with select2 in my fixed div popup that acts like a modal. The problem is that when the select2 dropdown is open, I am unable to scroll the div until I close the dropdown. This becomes problematic on smartphones because the keyboard e ...

Is the promises functionality respected by the Nextjs API?

Greetings, I hope all is well with you. I am currently learning NEXTJS and working with its API, but I have encountered a problem. When I click too quickly, the promises seem to get stuck or encounter issues. You can see the tests in action in this brief 3 ...

Having trouble connecting to the Brewery API, could use some guidance from the experts (Novice)

I'm currently facing some difficulties connecting to a brewery API (). I am developing a webpage where users can input the city they are visiting and receive a list of breweries in that city. As someone unfamiliar with APIs, I am unsure about the nece ...

Utilizing Chart.js to visualize live data from a dynamic MySQL dataset

Struggling to create a dynamic dataset for my Chart.js project, specifically with the data obtained from getpromorevenuechart.php. Here's an example of the dataset: [{"mmyy":"2019-12","promocode":"promo1","amount":"2776"},{"mmyy":"2020-01","promocode ...

Encountered issues loading JavaScript and received a pyppeteer error while trying to access a website through requests

I am facing a challenge when trying to scrape a webpage post login using BeautifulSoup and requests. Initially, I encountered a roadblock where the page requested JavaScript to be enabled to continue using the application. To work around this issue, I de ...

Issues with invoking C# event through ajax communication

Whenever I click the Button, an Ajax method is called that triggers a webmethod on the server side. However, currently, the [WebMethod] is not being executed as expected. Below are the snippets of both the Ajax and server-side code: Ajax code $(document ...

Utilize Bootstrap DataTable Sparkline to extract information from a comma-delimited string rather than an array

I have successfully implemented a Bootstrap DataTable component in my Asp.net Core MVC App to display data from my database. However, I am facing a challenge when trying to add a sparkline to a column. The sparkline component requires an array of values, b ...

After clicking on a specific href element with a designated class, trigger the display of a custom dialog styled using CSS

I recently added a unique class to certain links on my website. When these specific links are clicked, I want them to trigger a customized dialog box. My goal is to modify the CSS of this special dialog box. Only links with this particular class should ...

Activate video in Slick Slider with the click of a button

I am facing an issue with my slider setup, where each slide contains a video as the background along with play/pause buttons. When I try to play the video by clicking the corresponding button on a specific slide, I encounter this problem: if I click the pl ...

Troubleshooting lack of output in Console.log (NodeJs)

I am facing an issue where I can't see any output when trying to console log a JavaScript code using Node.js. const pokemon = require('pokemon'); pokemon.all(); var name = pokemon.random(); console.log(name); I am unable to even display a ...

What happens when the cookie fork refuses to display the values I have set for my cookie?

<?php if (isset($_POST['pieslegsanas'])){ require '../conn.php'; global $conn; $email = $_POST['epasts']; $password = $_POST['password']; $sql = "SELECT * FROM user_acounts WHERE e_past ...

Encountering a 403 error when sending a POST request from an Android app to a Django server

Currently, I am diving into the world of networking on android using a django server. I have successfully tackled GET requests and receiving JSON responses, also managed to obtain the CSRF cookie. However, when attempting a POST request with the cookie inc ...

The value of 'this.selectedNodes' does not support iteration and is causing a

I am currently utilizing v-network-graphs to generate graphs in the front end with Vue. I have set up my data like this: data(){ return{ test: test_data, nodes:{}, edges:{}, nextNodeIndex: Number, selectedNodes: ref<st ...

Retrieve information from a database by utilizing AJAX and store it in a JavaScript array

I'm facing an issue where I can retrieve data from the PHP file, but not from the database to my JavaScript code. I am using Ajax to fetch the data from the database, then passing it to the PHP file, and finally trying to filter this data using JavaSc ...

Creating multiple tables in an HTML template using loops, either with or without JavaScript, each table identical to the one previously created

<html> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3. ...

Wondering how to go back to the default locale in Next.js?

Within my Next.js application, I have successfully implemented the next-i18next module for multi-language support. The app currently supports two languages: English and Arabic, with English set as the default. To allow users to toggle between languages, I ...

After the completion of the JavaScript timer, the existing text remains in place even when the new text is displayed

https://jsfiddle.net/zLfuwdtu/1/ I've developed a script that tracks down to date 'Date1'. As it counts down, it shows the message "UNTIL FLOW." Once this timer reaches zero, another timer 'Date2' takes its place and displays "ON ...

Tips for adjusting the time interval on an automatic slideshow when manual controls are in play

I'm having trouble with my slideshow. I want it to run automatically and also have manual controls, but there are some issues. When I try to manually control the slides, it takes me to the wrong slide and messes up the timing for the next few slides. ...