Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I serve static files while providing an API for the server?

So I'm pretty new to web development and now that me and my much more web oriented friend started a project, he threw all kind of frameworks on me. We're doing Vuejs, jade, stylus, and jeet. For a newcomer, this is of course very confusing as no Vuejs examples uses jade, no jade examples uses vuejs, etc.

However, for this project we need a backend which can handle api calls to Google maps, saving stuff, etc. Neither of us have experience doing this and I tried to build it in Rust and got it all working with the api part but I couldn't manage to serve the files, leading to us trying a http-server serving the files and then making api calls to the Rust backend from the client. This led to problems as we had to do CORS requests (?) which I didn't get to work.

Sorry for the long background, it all boils down to the question: How do I serve static files while having the possibility to make api calls to Google Maps and store stuff in a database? All examples I find seems to assume that you're using templates to generate the files served to the end user?

How do I attack this problem? My friend has finished most of the frontend and it works simply by using the npm package "http-server"

like image 539
mnordber Avatar asked Sep 07 '25 04:09

mnordber


1 Answers

Important part is inside app.js file make sure yours server routes are defined up top and then client build static files afterwards like below.

var express = require('express');
var bodyParser = require('body-parser');
const path = require('path');

// put server express routes at the beginning //
var app = express();
var router = require('./routes')(); 
app.use('/api', router);
// put server express routes at the beginning //

//Serve the static files from the React app
app.use(express.static(path.join(__dirname, '/../build')));
// Handles any requests that don't match the ones above
app.get('*', (req,res) =>{
    console.log(res);
    res.sendFile(path.join(__dirname+'/../build/index.html'));
});

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.port || 3300

app.listen(port, () => {
    console.log("Hi This port is running");
});

app.get('/', function(req, res){
    if(req.session){
        console.log(req.session);
    }
    console.log('ok');

});

Also inside package.json file,

Add proxy to route it

"proxy": "http://localhost:3300",
like image 53
shailesh gavathe Avatar answered Sep 10 '25 01:09

shailesh gavathe