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!