React Scripts Not Found When Using GoLang http.FileServer

I am working on a Golang database project, in which I would like to use React to create the front-end. I am using react scripts linked to my index.html.

When I open my index.html directly, my react scripts work and the page is properly formatted. However, when I try to open the page through my server, the scripts are not found and I get a 404 error:

::1 - - [15/Feb/2017:16:16:24 -0500] "GET /build/react.js HTTP/1.1" 404 19

In order to access the index.html from my Golang server I use Gorilla Mux and http.FileServer:

import{ ... "github.com/gorilla/mux" ...}

main{ 
...
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./views")))
...
}

I am thinking the issue is with using the http.FileServer to access the html. I have tried locating my build folder in variety of locations, most recently within the views folder, always with the same result, that when opening the html directly the react scripts work, but they do not work when the html is accessed by my server.

Is there another method I should be using to accomplish this, or is it a problem with how I am organizing my dependencies?

What local dir does the URL path /build/ map to?

I am not sure. Build is a folder in the file system of my project. I do not think it is mapped to a URL path. Build is referenced in the HTML as

<script src="build/react.js"></script>
<script src="build/react-dom.js"></script>

Hey @thegrinch,

You would have to also be serving the directory containing the javascripts.

Here’s an example that I gave to someone who had the same problem you’re having but for css: Serving CSS files

Assuming that build is besides ./views in your project, adding a second handler using StripPrefix should do the trick:

r.Handle("/", http.FileServer(http.Dir("./views")))
r.Handle("/build/", http.StripPrefix("/build/", http.FileServer(http.Dir("./build"))))

(You would need to adapt this to match the actual path of the build directory.)

I solved this issue by adding:

r.PathPrefix("/build/").Handler(http.StripPrefix("/build/", http.FileServer(http.Dir("./build/"))))

in my main function in order to serve the react scripts. My file structure is:

main.go
views
-- index.html (views/index.html)
build
-- react.js (build/react.js)
-- react-dom.js (build/react.js)
-- other react scripts...

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.