CORS Issue with Golang Gin Gonic backend for a React Native app

Are you having trouble with your React Native app calling an API on your local machine? You’ve tried every mode ‘cors’ and ‘no-cors’ for the fetch request? For some reason, you’re seeing a 200 HTTP response but the message is empty?

If you’re using Golang’s Gin Gonic framework for your backend there’s one more step you need to do and that’s add the CORS middleware to your router.

This StackExchange post is pretty straightforward. Import the middleware

import (
    "net/http"

    "github.com/gin-gonic/gin"
    cors "github.com/rs/cors/wrapper/gin"
)

Then when you instantiate the router use the middleware like this:

router := gin.Default()
router.Use(cors.Default())

You should be able to see the backend response in the React Native client now. Try printing to the console with the fetch function like this:

   fetch('http://localhost:8080/register', data)
        .then(response => {
            if (response.headers.get('content-type').match(/application\/json/)) {
                return response.json();
            }

        })
        .then(json => {
            console.log(json);
            return json;
        })
        .catch(error => {
            console.log(error)
        })

Leave a Comment