Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node GET method doesn't accept combination of constants and strings

I have created an environmental variable that I want to use by concatenating it with a string for api route. I seem to have defined everything but for some reason combining both generates an error but using each of them separately works fine and I don’t understand why. For example this works

app.get(``${api}``,(req, res) => {}); or app.get(`/products`,(req, res) => {});

but app.get(`${api}/products`,(req, res) => {}); doesn’t work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.env

API_URL = /api/v1/

app.js

const express = require("express");
let app = express();
require("dotenv").config();

const api = process.env.API_URL;

app.get(`${api}/products`, (req, res) => {
  const product = {
    id: 1,
    name: "shoes",
  };
  res.send(product);
});

app.listen(3000, () => {
  console.log(api);
  console.log("Server is running on http://localhost:3000");
});

ERROR : Cannot GET /api/v1/products

>Solution :

You’re declaring a route for /api/v1//products. Notice the double-slash in there.

Either remove the trailing slash from your environment variable, or remove the leading slash from /products.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading