Giter Club home page Giter Club logo

Comments (10)

jackgris avatar jackgris commented on June 16, 2024 2

@muhammadqazi I think your error is related to this line .then(response => response.json()) in the fetch without Axios. You are trying to parse the pong response to JSON, also the header is not ok. If you see your code with Axios, you never specified that the response is in JSON format.
You could try something like this:

.then(response => {
    console.log(response)
    response.json()
})

And see the response before trying to parse it to JSON. If you receive it right there, you need to change your endpoint to return a JSON, or in that fetch use response. text() javascript doc In the repo I created you can see I use response.text() You don't see the parse JSON error in the console?

from mux.

jackgris avatar jackgris commented on June 16, 2024 1

Hi @muhammadqazi, both examples work for me, the only error a found was when you write the handler using the mux library in the path, you forgot the / in the path, it must be /ping. Maybe was a copy-paste error here, you wrote:

// test route
    r.HandleFunc("ping", func(rw http.ResponseWriter, r *http.Request) {
        rw.Write([]byte("pong"))
    })

And mus be:

// test route
    r.HandleFunc("/ping", func(rw http.ResponseWriter, r *http.Request) {
        rw.Write([]byte("pong"))
    })

In both cases, I don't get a CORS error.

from mux.

muhammadqazi avatar muhammadqazi commented on June 16, 2024 1

Hi @muhammadqazi, both examples work for me, the only error a found was when you write the handler using the mux library in the path, you forgot the / in the path, it must be /ping. Maybe was a copy-paste error here, you wrote:

// test route
    r.HandleFunc("ping", func(rw http.ResponseWriter, r *http.Request) {
        rw.Write([]byte("pong"))
    })

And mus be:

// test route
    r.HandleFunc("/ping", func(rw http.ResponseWriter, r *http.Request) {
        rw.Write([]byte("pong"))
    })

In both cases, I don't get a CORS error.

yeah thats a copy/paste mistake, but mux and gin both are not working for me in any case except postman

package main

import (
	"context"
	"net/http"
	"os"
	"time"



	"github.com/golang-migrate/migrate/v4"
	_ "github.com/golang-migrate/migrate/v4/database/postgres"
	_ "github.com/golang-migrate/migrate/v4/source/file"
	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
	"github.com/jackc/pgx/v5/pgxpool"
	_ "github.com/mattes/migrate/source/file"
)

func main() {





	

	r := mux.NewRouter()

	r.HandleFunc("/ping", func(rw http.ResponseWriter, r *http.Request) {
		rw.Write([]byte("pong"))
	})


	
	ch := handlers.CORS(handlers.AllowedOrigins([]string{"*"}))

	s := http.Server{
		Addr:         "localhost:9000",
		Handler:      ch(r),
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
		IdleTimeout:  120 * time.Second,
	}

	logger.Info("Server started at port", env.PORT)

	err = s.ListenAndServe()
	if err != nil {
		err = tracerr.Wrap(err)
		tracerr.PrintSourceColor(err)
		os.Exit(1)
	}

}

from mux.

muhammadqazi avatar muhammadqazi commented on June 16, 2024 1

@jackgris Thanks man, it's working, I removed the header and just console the response.

from mux.

itsdeekay avatar itsdeekay commented on June 16, 2024

Hi @muhammadqazi I used your example above and I didn't get any CORS error. I can do Ping on browser, postman and fetch from browser console. Here is the code I have used:

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
)

func YourHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Ping!\n"))
}

func main() {
	r := mux.NewRouter()
	// Routes consist of a path and a handler function.
	r.HandleFunc("/ping", YourHandler)

	// Bind to a port and pass our router in

	ch := handlers.CORS(handlers.AllowedOrigins([]string{"*"}))
	//log.Fatal(http.ListenAndServe(":8000", ch(r)))
	s := http.Server{
		Addr:         "localhost:8000",
		Handler:      ch(r),
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
		IdleTimeout:  120 * time.Second,
	}

	log.Fatal(s.ListenAndServe())
}

Could you help us understand where is the problem or if I am doing something different. It would be better if you can write steps to replicate with complete code.

from mux.

muhammadqazi avatar muhammadqazi commented on June 16, 2024

@itsdeekay

Screenshot 2023-07-21 at 4 01 11 PM Screenshot 2023-07-21 at 4 01 34 PM

I used the same code, its working with postman but not with React js applicaiton.

from mux.

itsdeekay avatar itsdeekay commented on June 16, 2024

@muhammadqazi could you also share the React JS request?

from mux.

jackgris avatar jackgris commented on June 16, 2024

@muhammadqazi I created a tiny and silly project of a React app created with Vite, it only has a button that calls the ping endpoint and works fine: test cors gorilla mux it only changes the text of the button, when receiving the pong response.
Inside also is the Go code of the endpoint.

from mux.

trevatk avatar trevatk commented on June 16, 2024

@muhammadqazi was having the same issue, kind of difficult to troubleshoot without seeing your react code. But what worked for me was to set the AllowedOrigins prefixed with http://* or https://*. The preflight check isn't needed.

Also had to set the Content-Type: application/json manually. But on the react side I use the createApi function.

from mux.

muhammadqazi avatar muhammadqazi commented on June 16, 2024

@itsdeekay That's my reactjs code, it's not working with the fetch() but i tried in axios now and it worked.

fetch("http://localhost:9000/ping", {
      method: "GET",
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(response => response.json())
      .then(data => {
        // Handle the response data
        console.log(data);
      })
      .catch(error => {
        // Handle any errors that occurred during the request
        console.error("Error:", error);
      });

Axios

    axios.get("http://localhost:9000/ping").then(response => {
      console.log(response);
    });

from mux.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.