Avoid API calls by using connect-history-api-fallback

I have implemented the connect-history-api-fallback along with the page.js router.

page('/', index);
page('/about', about);
page();

function index() {
    console.log("viewing index");
}

function about() {
    console.log("viewing about");
}

The routing functionality is working correctly, but there seems to be an issue when trying to access the API as the routing interferes with the call.

GET localhost:4000/            # invokes index view function
GET localhost:4000/about       # invokes about view function
GET localhost:4000/api/todos   # Does not return JSON data as expected

Below is the configuration for the server setup...

const express = require("express");
const history = require('connect-history-api-fallback');

var todos = require("./api/routes/todos");

var app = express();

// Allowing requests from all domains and localhost
app.all("/*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header(
        "Access-Control-Allow-Headers",
        "X-Requested-With, Content-Type, Accept"
    );
    res.header("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE");
    next();
});

const root = `${__dirname}/app/dist`

app
    .use(history())
    .use(express.static(root))
    .use(express.json())
    .use(todos)
    ;

var server = app.listen(4000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log("App is now listening at http://%s:%s", host, port);
});

Answer №1

This is the solution.

app.use(history({
    rewrites: [
      {
        from: /^\/api\/.*$/,
        to: function(context) {
            return context.parsedUrl.path
        }
      }
    ]
 }))

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

Javascript - Issue: Route.post() is in need of a callback function, however it received an [object Promise] instead

I'm encountering an issue with one of my express routes. The error message I am receiving is as follows: Error: Route.post() requires a callback function but got a [object Promise] This error seems to be related to the last line in controllerFunction ...

Has Angular been assimilated into the window object by webpack?

I'm encountering a puzzling issue with webpack that I can't seem to resolve. Here is the link to my webpack.config file: https://github.com/saike/maluvich-browser/blob/master/webpack.config.babel.js In my project, I import angular using ES6 mo ...

I'm encountering a typescript error as I migrate a Paho MQTT function from Angular 1 to Angular 2 - what could be causing this issue?

When connecting to my MQTT broker, I am working on several tasks. In my Ionic 2 and Angular 2 application, I have created an MQTT provider. Here is the provider code: import { Component } from '@angular/core'; import { NavController, ViewControl ...

Tips for detecting the existence of scrollbar on a webpage and retrieving its coordinates

I am working on a web page where I need to dynamically retrieve the scroll coordinates of the page. If a page has multiple scrolls, I should be able to get the respective scroll coordinates for each. The functionality needs to adjust based on the specifi ...

The backdrop moving in a reverse direction

I recently made a tweak to this code that successfully moves the background in the opposite direction of the scroll. However, there is now an issue where it leaves a blank space at the top, even when the background is set to repeat. The change I made was s ...

Issue encountered while requesting data from API in ReactJS

I've been trying to fetch data from using the react useEffect hook. However, instead of displaying the data, I keep getting an error message that says, "Error: Objects are not valid as a React child (found: object with keys {number, name}). If you me ...

Mongoose Error: Incompatible receiver called Method Uint8Array.length

I am currently working on a small website that incorporates i18n. Initially, I used local json files, but upon transitioning to mongodb, I encountered an unfamiliar error. Any detailed explanation of this issue would be greatly appreciated. The specific e ...

While the data from Angular $resource can be viewed, it is not accessible in the code

As a newcomer to Angular, I'm facing a frustrating issue that I need help with. My $resource is fetching data from the server in key/value pairs like detail.name and detail.email. While I can access this data using {{detail.name}} in the view, I&apo ...

What's the reason why Angular stops flickering with the use of "/" in href?

Recently, I've come across a peculiar issue in one of my web applications while using Angular's routeProvider as a template engine. The app functions properly, but the behavior seems inexplicable to me. The problem arises during page transitions ...

Attempting to integrate a real-time website link in ReactJs

Need help adding a live website URL like "https://covid19statswebsite.netlify.app/" to my Button so that clicking on it redirects to the specified URL. Any suggestions on how to achieve this? Here is the Button code snippet: import React from "react"; imp ...

Building a secure authentication system using Node.js Passport, Local token, and MySQL database

I'm looking for a way to allow users to start a session using just a token, without needing to enter a password. Currently, I am utilizing the passport-local-token module. Check it out here: https://www.npmjs.com/package/passport-local-token Howeve ...

Issue with installing vscode-ripgrep during VSCode build/run process

After attempting to build and run VSCode on my Ubuntu 17.10 by following the instructions from this guide: https://github.com/Microsoft/vscode/wiki/How-to-Contribute#build-and-run, I encountered an issue when installing dependencies using yarn. The error m ...

Guide to executing a PUT request using Node.js

Here is the code snippet from my app.js file: import bodyParser from 'body-parser'; import cors from 'cors'; import requestIp from 'request-ip'; import os from 'os'; import { AppRoutes, AuthRoutes } from './rou ...

Activate the Giphy search feature in the Slack Nestor bot's response

How can the nestor bot be configured to use a giphy search when replying in a Slack channel where the giphy plugin is active? Can something like msg.reply('/giphy ' + text, done); be used for this purpose? ...

What is the best way to evaluate a sequence of actions and their outcomes?

Recently, I've dived into the world of writing automated tests for a React application. Along the way, I encountered some intriguing questions about the best approach to testing a series of interactions within the app. Let's imagine a scenario w ...

Implementing Axios interceptor is a common practice in Vue.js applications to central

Hello everyone, I'm facing a problem with the interceptor in VueJS. I can't seem to figure out where the issue lies and it's driving me crazy... I've gone through various tutorials and read numerous posts on stackoverflow, but everythi ...

I am perplexed as to why my application is yielding an undefined response

After incorporating the code snippet into my app.js on the express server app.get('/*', function (req, res) { res.sendFile(path.join(publicPath, 'index.html')), function(err) { if (err) { res.stat ...

Can AngularJS routes be defined with templateUrl paths that are completely independent of the IIS app's folder structure?

I have been conducting research both here and in general, but so far, I haven't found a suitable way to implement this. Our web application uses MVC/WebAPI2/AngularJS. The goal I'm aiming for is to be able to place my app anywhere within the II ...

Retrieve the ID from either a search query or an insertion operation in MongoDB

I find myself frequently using this particular pattern. It feels a bit cumbersome to make two MongoDB calls for the task, and I am curious if there is a more efficient way to achieve this. My goal is to obtain the ID of an existing document, or.. create ...

What is the best way to organize angularjs controllers and directives within one another?

When I structure my controllers like this: <body ng-app="app" ng-controller="ctrl"> <div ng-controller="app-get"> <app-get></app-get> </div> <div ng-controller="app-post"> <app-post">& ...