Unable to establish connection with an API endpoint on my Express server

Exploring the world of Express for the first time, I'm currently facing difficulties in establishing a connection to an API.

Below you can find the code snippet that's causing me trouble:

const express = require("express");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const flash = require("connect-flash");
const fetch = require("node-fetch");
const axios = require("axios");

const app = express();
const dotenv = require("dotenv");
dotenv.config();
let sessionOptions = session({
  secret: "Javascript is so cool",
  store: MongoStore.create({ mongoUrl: process.env.CONNECTIONSTRING }),
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 1000 * 60 * 60 * 24, httpOnly: true },
});

app.use(sessionOptions);
app.use(flash());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static("public"));

app.set("views", "views");
app.set("view engine", "ejs");
const router = require("./router");
const apiRouter = require("./apiRouter");

const options = {
  url: "https://rms.pythonanywhere.com/api",
  method: "",
  json: {},
};

app.use("/", router);
app.use(options.url, apiRouter);

module.exports = app;

The following is the route file created for connecting with the API:

const express = require("express");
const apiRouter = express.Router();
const request = require("request");
const fetch = require("node-fetch");
const userController = require("./controllers/userController");
const pageController = require("./controllers/pageController");

apiRouter.post("/user/create", async function (req, res) {
  const api_url = "https://rms.pythonanywhere.com/api";
  const fetch_res = await fetch(api_url, options);
  const json = await fetch_res.json();
  res.json(json);
});

module.exports = apiRouter;

Upon submitting my registration form, I aim to send a POST request to the API URL and receive its response. However, each attempt results in an error message stating (can't send post request to /user/create).

My ultimate goal is to establish a connection with the API link (rms.pythonanywhere.com/api), directing routes for registration, login, and other functionalities through this interface. Struggling with this challenge for more than a week now, any help or guidance from experienced individuals would be greatly appreciated. Thank you in advance!

Answer №1

It appears that your express application is having trouble locating the apiRouter. To resolve this issue, make sure to utilize the express router by using the express.use() method first.

To implement this, simply include the following line in your code:

express.use("/", apiRouter); 

Answer №2

Thank you all for your input. While none of the responses provided a direct solution, they did point me in the right direction.

To resolve my issues, I decided to utilize the axios library. By installing it from the npm store and requiring it in my code with required("axios"), I was able to incorporate it into my apiRouter.post("/user/create") route. Here is an overview of how I tackled the problem:

apiRouter.post("/register", async function (req, res) {
  const api_url = "https://rms.pythonanywhere.com/api";
  axios.post(api_url + "/user/create/", {
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    email: req.body.email,
    password: req.body.password,
    user_type: req.body.user_type,
    username: req.body.username,
}).then((response) => {}).catch((error){})

});

By implementing this approach, I successfully managed to send the data from my post request within apiRouter.post(/register) and handle the corresponding success and error responses within the then() and catch() blocks, respectively.

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

Firefox Issue: SetTimeout Redirect Function Not Functioning Properly

Working on a page that redirects users to an installed application or a webpage as a fallback. This is implemented using ClientScript.RegisterStartupScript when the page loads, with a Javascript snippet like this: <script type='text/javascript&apo ...

Tips for integrating Google Analytics with React

In my react application, I have various pages: Main Service Contact Profile (private) etc.. To monitor user activity using Google Analytics, I came across the react-ga library which serves the purpose well. However, I find myself having to initialize G ...

Avoiding type errors in d3 v5 axis by using Typescript

I am new to TypeScript and I have some code that is functioning perfectly. I believe if I define a type somewhere, d3's generics will come into play? Within my code, I have an xAxis and a yAxis. Both are the same, but D3 seems to have an issue with t ...

PHP form submission upon conditions being satisfied

I am not utilizing Javascript as it is disabled in my current environment. Here is the code that I would like you to review. I am attempting to use PHP to replicate the functionality of Javascript or jQuery's simple : document.form2.submit() <div ...

Default cross-origin behavior of the Fetch API

According to the Fetch Specifications, the default Fetch mode is 'no-cors'. The specifications state that a request's mode can be "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless otherwise specified, it defaults to "no ...

The Express JS is having trouble serving the static CSS files through the router

Currently, I am encountering this issue in a larger project, so I have created a simplified version to explain it more clearly. The Tree Structure of my project is outlined below: demo |____admin | |____admin.js |____node_modules | |____static | ...

NodeJS URL Parsing Deprecated

Looking for a solution to update the URL parse method on Node v14 and Express v4. I've made some attempts but haven't been successful. const { URL } = require('url'); const myURL = new URL(req.url, 'http://example.com'); const ...

Send users from the web (using JavaScript) to the Windows Phone app, and if the app is not installed, direct them

In the following code snippet, I am using angular.js to detect the mobile platform and redirect to the native app. If the app is not installed, it will redirect to the market: $scope.isMobile = { Android: function() { return navigator.userAgent.ma ...

How can two distinct sachems be returned in an http get request using res.json()?

There are two schemes that I have created: Sales and Abc I would like to send a response that includes the documents for both schemas: router.get('/', function(req, res) { Sales.find(function (err, sales) { if (err) return next(err) ...

XHR object encountered a 404 error while attempting a GET request with an unknown URI component name

Currently, I am attempting to design a text box that triggers a server query as soon as a character is entered into it. However, I am encountering an error message that is puzzling me: Traceback (most recent call last): File "/Users/sahandzarrinkoub/Do ...

Utilize Google Console with Chrome and jQuery to extract the name and URL from HTML content

I am trying to parse the HTML source code in order to extract all links and text from it, and then store this information in a multidimensional array, all within the Google Chrome console. Here's a snippet of the code that needs to be repeated 10 tim ...

Avoiding mistakes in class and id names with preventative tools

Is there a simple way to spot typos in HTML/CSS/JavaScript code? I'm looking for basic debugging tools that can catch mistakes like "#fron" instead of "#from" in class names and ids. I'm aware of more advanced IDEs, but I'm curious if there ...

Error message saying "Unable to access 'map' property of undefined" occurs after updating state in ReactJS

Currently facing a challenge while updating the state. I have confirmed that the data obtained from the API is accurate as I verified it with console.log(). Strangely, the error occurs only during searches with more than one letter. I attempted to resolve ...

A guide on adding a hyperlink to a table in Node.js using officegen

Currently, I am utilizing a widely-used Node.js library for generating MS Office Word documents. In the officegen module, the code below is used to create a table. When a raw string is provided to the 'val' property inside the table, it generate ...

Preventing AngularJS from Binding in Rows: A Solution

Currently, I am utilizing AngularJS version 1.5.3 and I am facing an issue with my services. I have two services - one that retrieves Area names and the other that fetches details for each Area. In my code, I first call the service to get the Area names an ...

Is it beneficial to display three.js on a <canvas> rather than a <div>?

I have come across examples in three.js that use: renderer = new THREE.WebGLRenderer( { canvas: document.querySelector( 'canvas' ) } ); This relates to a <canvas></canvas> element. On the contrary, there is another method: rendere ...

Display drop-down item when selected for the first time and hide it when selected for the same item for the second time

Is there a way to display form input when "C" is selected and hide it when "A", "B", or "D" are selected? If "C" is selected again after initially showing the form input, should it be hidden? For example, if "C" is selected for the first time, the form inp ...

Invoke the parent's function within the Local-Registration component of VueJs

I have a Vue object: var app = new Vue({ el: '#my-id', data() { return { example: 1 } }, methods: { exampleMethos(data) { console.log('data', data); } }, ...

Choosing a class using Jquery through a For loop in Javascript

I have a group of images with a class applied to them. I am attempting to create a for loop that will iterate through the elements of this class. In Python, you can use "for element in thing" and I was curious if there is something similar in JavaScript. A ...

Feed JSON data into a jQuery function using JavaScript

A rudimentary Google Apps Script Web App has been created with the sole purpose of displaying JSON data in an HTML drop-down list. The JSON file is stored in Google Drive. Code inspiration taken from: http://jsfiddle.net/manoj_admlab/Mta5b/3/ However, we ...