Trouble with setting up custom static route

Greetings! I am currently working on setting up my project in React and here is my current project structure:

-public
--w
---dist
----bundle.js
---index.html
-server
--server.js
-src
--app.js
-webpack.config.js
-package.json
-.babelrc

For my server, I am using Node.js. I want my static files to be called on localhost:port//w/ and API calls on localhost:port//api/.

I have made attempts at tweaking server.js, routes, project structure, and webpack.config but haven't achieved success yet.

Here's a snippet from my server.js:

(...)

And this is how my webpack.config looks like:

(...)

As for my routes:

(...)

If anyone has any suggestions on what steps I should take or if there's something crucial missing, please feel free to advise me.

Answer №1

If you want to improve efficiency, a restructuring is necessary.

-public
--dist
---bundle.js
--index.html
-server
--server.js
-src
--app.js
-webpack.config.js
-package.json
-.babelrc

Server.js

const express = require('express');
const path = require('path');

const app = express();
const port = 3000;
const publicPath = path.join(__dirname, '../public');

app.use(express.static(publicPath));

// make sure all APIs are set before using fallbacks
app.get('/api/test', (req, res) => {
    res.send("Hello");
});

app.get('/w/*', (req, res) => {
    console.log('Calling..');
    res.sendFile(path.join(publicPath, 'index.html'));
});

app.listen(port, () => {
    console.log(`The server is now running on port ${port}`);
});

webpack.config.js

const path = require('path');

module.exports = {
    entry: './src/app.js',
    output: {
        path: path.join(__dirname, 'public', 'dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            { 
                test: /\.js$/, 
                use: 'babel-loader', 
                exclude: /node_modules/
            }
        ]
    },
    devtool: 'inline-source-map',
    devServer: {
        contentBase: path.join(__dirname, 'public'),
        publicPath: '/dist/',
        historyApiFallback: true
    }
}

It's important to maintain your routes as they are.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

npm fails to function properly following the execution of the 'npm install' command

After downloading and installing node.js + npm from https://nodejs.org/en/, I created a project folder and navigated into it on Windows 10. However, when I attempted to run the command: C:\nodejs\demo>npm install <a href="/cdn-cgi/l/email- ...

unable to implement multiple layouts while utilizing react-router

My current project requires two different layouts: one for the homepage (currently implemented in app.js) and another for the result page. After submitting a form, the results should be displayed in the result layout instead of the app layout. However, whe ...

Change PHP code to a JSON file format

I am currently learning Laravel and my current focus is on how to send a JSON file from the back end to the front-end. I intend to utilize this JSON data to generate a graph. Within my model, I have created a function that retrieves values and timestamps ...

The Angular scope remains stagnant even after applying changes

Having trouble updating a variable in the ng-repeat loop <div ng-controller="MapViewCtrl"> <a class="item item-avatar" ng-href="#/event/tabs/mapView" > <img src="img/location.jpg"/> <span cl ...

Having difficulty incorporating custom JavaScript files into a testing framework

I am facing a unique challenge while integrating the Page Object design pattern into my test suite using selenium-webdriver and node.js. The first page object, pageObject/admin/login/index.js, works seamlessly. It contains selectors and methods to fill ou ...

Attempting to fetch package from an unconventional repository via npm install

When I work on my Node project at the office on a Mac, everything runs smoothly. However, when I try to work on it from home on a Windows machine, I encounter an access rights error while attempting to run npm install. Within my package.json, I have liste ...

Using Rails AJAX to dynamically load partials without the need to submit

Imagine creating a dynamic page layout with two interactive columns: | Design Your Pizza Form | Suggested Pizzas | As you customize your pizza using the form in the left column, the right column will start suggesting various types of pizzas based on your ...

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...

Successive vows

I'm trying to retrieve responses from four promises, but I currently have to call each function in sequence one after the other. In my code, you can see that I trigger the next function within the promise callback of the previously called function. H ...

Checking for the existence of a row in Node.js using Sqlite3

Wondering if it's possible to verify the existence of a row using node.js and the sqlite module. I currently have this function in place, but it always returns false due to the asynchronous nature of the module. function checkIfRowExists(username, pa ...

Search for records in MongoDB where the time is below a specified threshold

content of the document is provided below chatid:121212, messages:[ { msg:'Hello', time:'2021-04-17T16:35:25.879Z' }, . . . ] I am looking to retrieve all records where the timestamp is earlier than a ...

Error encountered with TypeScript compiler when using a React Stateless Function component

I am attempting to create a React Stateless Function component using TypeScript. Take a look at the code snippet below: import * as React from 'react'; import {observer} from 'mobx-react'; export interface LinkProps { view: any; ...

When utilizing the package, an error occurs stating that Chart__default.default is not a constructor in chart.js

I have been working on a project that involves creating a package with a react chart component using chart.js. Everything runs smoothly when I debug the package in storybook. However, I encountered an error when bundling the package with rollup, referenc ...

The definition of "regeneratorRuntime" is missing in the rete.js library

After encountering a problem, I managed to find a potential solution. My current challenge involves trying to implement Rete.js in Next.js while using Typescript. The specific error message that's appearing is: regeneratorRuntime is not defined Be ...

What is the best way to distribute shared client-side javascript code among NodeJS projects?

As a newcomer to Node, I am embarking on a journey with a few web app projects using Express. Across these projects, there are some client-side libraries that I would like to share. It seems like a common issue with many possible solutions already in exist ...

Some places may not have detailed information available when using the Google Places API

Greetings I am currently in the process of developing a page on my website that utilizes the Google Places API along with the user's geographical coordinates (latitude, longitude) to locate nearby restaurants. In my code, I have implemented a functio ...

Sharing application state between different routes in React Router v4 can be achieved by using methods such

I'm seeking solutions to address the following challenge: Without utilizing any state management library, I solely rely on React. The primary application state is contained within the <MyFoodApp/> component, which includes an array of restaura ...

Utilize the version designated in the package.json file for your NPM script

Currently, I am working on an npm script that involves starting up a server and building to a specific directory in my project. Within this directory, there is a sub-directory that matches the version of my app specified in the package.json file. { name: ...

The provided argument, which is of type 'RefObject<HTMLDivElement>', cannot be assigned to the parameter of type 'IDivPosition'

Currently, I am implementing Typescript with React. To organize my code, I've created a separate file for my custom function called DivPosition.tsx. In this setup, I am utilizing useRef to pass the reference of the div element to my function. However ...

The UNHANDLEDREJECTION callback was triggered prematurely during asynchronous parallel execution

Asynchronously using parallel to retrieve data from the database in parallel. Upon each task returning the data, it is stored in a local object. In index.js, the cacheService.js is called. Inside cacheService.js, data is loaded from both MySQL and MongoDB ...