Home > Back-end >  Node GET method doesn't accept combination of constants and strings
Node GET method doesn't accept combination of constants and strings

Time:08-10

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

.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

CodePudding user response:

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.

  • Related