skip to Main Content

I’m making simple web application of uploading the products. I have a server on GO, which has only one handler on POST method. I have some demontsration below:

package main

import (
 "encoding/json"
 "fmt"
 "github.com/gorilla/mux"
 "net/http"
)

type Product struct {
 Id int json:"id"
 Desc string json:"desc"
}

func productsPostHandler(w http.ResponseWriter, r *http.Request) {
 p := &Product{}
 json.NewDecoder(r.Body).Decode(p)
 fmt.Println(p.Id, p.Desc)
}

func main() {
 router := mux.NewRouter()
 router.HandleFunc("/products", productsPostHandler).Methods("POST")
 fmt.Println("Server is listening...")
 http.ListenAndServe(":8181", router)
}

And also, I have js client, a simple query to my server. I’m trying to upload the specific Product:

fetch("http://localhost:8181/products", {
 method: "POST",
 body: JSON.stringify({
 id: 1,
 desc: "The first product",
 })
 })
 .then(response => {
 console.log(response)
 })

When server and client try to interact, it failed with the CORS error below.

I want to avoid this error. I guess, I got to fix the http headers in the request somehow. I’ve tried to add the “Access-Allow-Origin” and nothing happened. So, I’m asking for your help.

2

Answers


  1. This package https://github.com/rs/cors will help you to setup cors in your golang application.

    Login or Signup to reply.
  2. It should not happen, because server and client are in the same domain.
    Try changing "localhost" in client for "127.0.0.1", as this:

    fetch("http://127.0.0.1:8181/products", {
       method: "POST",
       body: JSON.stringify({
          id: 1,
          desc: "The first product",
       })
    })
    .then(response => {
    console.log(response)
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search