Comments (10)
@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.
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.
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.
@jackgris Thanks man, it's working, I removed the header and just console the response.
from mux.
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.
I used the same code, its working with postman but not with React js applicaiton.
from mux.
@muhammadqazi could you also share the React JS request?
from mux.
@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.
@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.
@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)
- [bug] : the link for gorilla mux logo is broken
- [feature] Add CONTRIBUTING.md HOT 4
- [bug]
- [question] Is it true? Is the GWT unarchived, for real? HOT 3
- JSON parsing failed HOT 7
- [BUG] Go can't find v2.0 HOT 1
- [BUG] MethodNotAllowedHandler does not work for subrouter with different routes HOT 9
- [BUG] Router does not distinguish between `/` and `%2F` in the request path HOT 1
- Cannot install gorilla/mux with new install command of go HOT 2
- [BUG] Index out of range in (*routeRegexp).Match HOT 1
- [FEATURE] Accidental omission of GetHeaders? HOT 1
- [BUG] API is probably broken for GetQueries per each method HOT 1
- [BUG] runtime error in (*routeRegexp).Match
- [FEATURE] Route metadata
- When I use the subrouter() method, Methods() only works on the last endpoint, and other than the last endpoint, the rest of the endpoints give a 404 instead of a 405 with the unrelated http method. HOT 3
- router.Host not working for me
- [FEATURE] Support multi-value query string parameters HOT 3
- [BUG] handler and middleware running twice with middleware defined on pointer reciever
- the Wrapped Gorilla Websocket connection by Gorilla Mux, does not work within the docker container.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mux.