When trying to access [Apiurl] from Vue and Golang, an error occurs due to the CORS policy blocking the XMLHttpRequest. The request header field 'authorization' is not allowed

As a newcomer to Vuejs and golang, I encountered an issue when attempting to send an Authorization token through the header while making an API call from Vue Axios.

The error message that was displayed is as follows: "Access to XMLHttpRequest at 'http://localhost:5000/greet/hello' from origin 'http://localhost:5500' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response."

[Although the actual error occurred in another project, I replicated it in a simple demo project for ease of understanding and troubleshooting purposes. Feel free to test the code on your end and provide a solution if possible.]

App.go

package main

import (
    "fmt"
    
    "github.com/gin-contrib/cors"
    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    router.Use(cors.Default())
    router.Use(Authenticate())

    v1 := router.Group("/greet")
    {
        v1.POST("/hello", handleFunc)
    }
    router.Run(":5000")
}

func handleFunc(c *gin.Context) {
    var student struct {
        Name string `json:"name"`
    }

    if c.BindJSON(&student) != nil {
        c.JSON(400, gin.H{"message": "Provide required details."})
        c.Abort()
        return
    }

    message := fmt.Sprintf("%s%s", "Good Morning ", student.Name)

    c.JSON(200, gin.H{"message": message})
}

func Authenticate() gin.HandlerFunc {

    return func(c *gin.Context) {

        requiredToken := c.Request.Header["Authorization"]

        if len(requiredToken) == 0 {
            c.JSON(400, gin.H{"message": "No token found"})
            c.Abort()
            return
        }

        fmt.Println(requiredToken)

        c.Next()
    }
}

index.html

<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
    </head>
    <body>
        <div id="app" class="container m-5">
            <p>{{name}}</p>
            <input type="text" class="form-control col-3" placeholder="Enter Name" v-model="name"/><br>
            <button @click="onButtonClick" class="btn btn-info">CALL API</button>
        </div>
        <script src="index.js"></script>
    </body>
</html>

index.js

var app = new Vue({
  el: '#app',
  data: {
    name: ""
  },
  methods: {
    onButtonClick() {
      axios
        .post("http://localhost:5000/greet/hello",
          {
            Name: this.name
          },
          {
            headers: {
              Authorization: "HEY"
            }
          })
        .then((response) => {
          if (response.status == 200) {
            alert(response.data.message);
          }
        })
        .catch((error) => {
          console.log(error);
          alert(error.response.data.message);
        });
    },
  }
})

Answer №1

Essentially, using Allowed-Origin: * with the Authorization header is prohibited. You must specify the allowed domain instead. To do this, modify the CORS middleware rather than relying on the default router.Use(cors.Default())

You can implement something like this:

router.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"http://localhost:5500"},
    AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},
    AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
    ExposeHeaders:    []string{"Content-Length"},
    AllowCredentials: true,
    MaxAge: 12 * time.Hour,
}))

You can also utilize the AllowOriginFunc property in cors.Config for a dynamic approach (if you need to support multiple domains).

Take note of how the AllowOrigin property includes the domain of your vue project. You have the flexibility to allow additional headers beyond those listed here, which were previously permitted by the Default configuration.

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

Issue with using @ symbol in src alias in vite/vue project causing malfunction

Recently, I set up a Vue3/TS project using the Vite CLI The configuration in my vite.config.ts is as follows: import vue from '@vitejs/plugin-vue' import { defineConfig } from 'vite' import path from 'path' export default de ...

Troubleshooting V-model errors within VueJS components

Just dipping into VueJS and trying out a chat feature from a tutorial. I noticed the tutorial uses v-model in a component, but when I replicate it, the component doesn't display on the screen and the console throws a "text is not defined" error. Strug ...

Checking CORS permissions with a pre-flight OPTIONS request

During development, I implement a middleware called cors using the following syntax: app.use(cors({origin: 'http://localhost:8100'})); However, I have noticed that for every route request, two requests are being made as shown in the image below ...

The absence of the 'Access-Control-Allow-Origin' CORS header was noticed in the response from the Wikipedia API

Attempting to retrieve data from the Wikipedia API using axios in reactJS. Here is my request: axios.get('https://en.wikipedia.org/w/api.php?action=opensearch&search=lol&format=json&callback=?') .then((response) => { c ...

"Implementing Vue mousemove functionality only when the mouse button is pressed

Is it possible to initiate a mouse movement only after the element has been clicked first? I am exploring this functionality for an audio player timeline. .player__time--bar(@mousedown="setNewCurrentPosition($event)") .slider(role="slider" aria-valuem ...

Is there a way to disable a row using ag-grid components?

Recently, while working with ag-grid, I came across documentation on how to disable a column (https://www.ag-grid.com/documentation-main/documentation.php). However, I couldn't find any information on how to disable just one specific row after going t ...

Access the data from a JSON object within a v-select menu

<v-form :model='management'> <v-flex xs3 sm2 md3> <div class="form-group> <v-select :items="days" item-text='text' item-value='text' placeholder="MM" single-line attach v- ...

What is the best way to incorporate jQuery and its plugins into a Vue component?

Is there a way to include jQuery plugins in a Vue application and use them inside the mounted hook? I know that jQuery can be imported via "import" inside a component (in the export default object) and is used in the life-cycle hook called "mounted." Howev ...

Vue.js - A dynamic parent component generates content based on data passed from a renderless child component

I am currently working on developing a system for generating buttons using vue 3 and vue-class-component. The main goal is to create a flexible button generation process, where the number of buttons generated can vary (it could be just one or multiple). Us ...

Utilize the key as the value for options within an object iteration in Vue.js

I have an object called colors, which stores color names: { "RD": "Red", "BL": "Blue", "GR": "Green", "YW": "Yellow" } In my dropdown menu, I'm generating options for each color in the colors object: <select v-model="colors"> <op ...

Tips for updating the Vue Multiselect options on display post a search query

I'm having issues with my Vue multiselect custom search function. It seems that when I search for text, the available options are updated behind the scenes, but they are not displayed to the user until an option is actually selected. How can I make su ...

Retrieve an uninitialized variable in Laravel using axios.post method within the Vue.js module

Hello partners! I'm collaborating with stackOverflow to develop a module using Laravel for the backend and Vue.js for the frontend. Currently, I am facing an issue where the controller is not receiving values from the form when creating a new entity. ...

How to remove unnecessary brackets from Vuetify's v-data-table when JSON data is empty

I am dealing with a list of data, and I have noticed that some objects in the dataset have an empty tag key field. While plotting this data in a table, the objects with a tag key display correctly, but those without it show up as []. How can I remove this ...

Adjust the displayed HTML Tag within a Vue Component to add variety

Is it possible to allow a user to choose which HTML tag will be rendered in a VueJS Component? For example, consider <my-component>Some Text</my-component>. I would like to create a property called "tag" that determines the HTML tag to render ...

Strategies for binding props to input values in Vuejs

Currently, I have a parent component called Cart where I have defined the quantity. My goal is to pass this quantity to the child component Counter. Below is how I am passing it within my parent component: <Counter quantity="item.quantity"/> ...

The event in Vue.js does not trigger for items that have been filtered out of the list

I currently have a list of items, each with a "complete" flag. Depending on the value of this flag, the item is displayed in either view A or view B. These items are fetched through an API request and then filtered client-side using a computed method based ...

setting a deadline for rendezvous with quasar version 1

Utilizing the quasar date component with restricted dates poses a challenge. In order to accomplish this, the documentation suggests utilizing the options prop which should be provided with an array or function. <template> <div class="q-pa- ...

Django CORS setup appears to be in order, yet still experiencing issues with CORS functionality

Attempting to send a POST request from a React Native Web front end to Django on different subdomains has proven to be challenging. Despite configuring CORS settings in Django correctly, it seems that something is still amiss. This is how my Django setti ...

Feeling lost when it comes to understanding how vue3 handles reactivity

Within vue3's reactive framework, there exists a stack known as the effectStack. I'm puzzled by the necessity of it being a stack if the effect is immediately removed with pop() after push(). Is there a scenario where the length of effectStack co ...

Encountering a problem while deploying Vue to GitHub Pages due to issues with vue-router

I encountered some difficulties while deploying a Vue application built with vue-cli v3.0 to GitHub Pages. I utilized subtree to only deploy the dist folder to the gh-pages branch. Initially, the issue was that the assets were not being found, but I resolv ...