So I am trying to build a small application that would serve a website and also the API for it. I am using Node, Express, and Webpack for that.
The directory looks somewhat like this:
>client
|>dist
|>src
>server
|>dist
|>src
>node_modules
package.json
webpack.config.js
Webpack bundles everything in each src
and spits it out in each dist
for both client
and server
.
When I access /
I want Express to serve the index.html
file in client/dist
. When I access /api
I need it to do other actions (those work fine).
This is how my server/src/app.js
file looks like (Who handles routing):
const express = require('express');
const path = require('path');
const port = process.env.PORT || 5000;
const app = express();
app.get('/', function(req, res){
res.sendFile(path.resolve(__dirname, 'client', 'dist', 'index.html'));
console.log('got hit on / boy');
});
app.get('/api/', function(req, res) {
//Does the right thing
})
app.listen(port, function(){
console.log('listening on ' + port);
})
And my Webpack file:
const path = require('path');
module.exports = [{
name: 'Client bundling',
entry: './client/src/app.js',
output: {
path: path.resolve(__dirname, 'client', 'dist', 'js'),
filename: 'bundle.js'
},
node: {
fs: 'empty',
net: 'empty'
}
},
{
name: 'Server bundling',
entry: './server/src/app.js',
output: {
path: path.resolve(__dirname, 'server', 'dist'),
filename: 'bundle.js'
},
node: {
fs: 'empty',
net: 'empty'
},
target: 'node'
}];
My follow up question would be how to access the API endpoint from the View served since they are both on the same domain.
Thank you!
You are pointing to a file that does not exist. Change this
res.sendFile(path.resolve(__dirname, 'client', 'dist', 'index.html')
to this
res.sendFile(path.resolve("../..", 'client', 'dist', 'index.html')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.