axios call node js express route with parameter

Viewed 72
const response = await axios(`http://localhost:9000/model/${id}`);

on my routes folder model.js

var express = require('express');
var router = express.Router();
const axios = require('axios');

router.get('/:id', function (req, res, next) {
// can't get here


});

on app.js

var modelRouter = require('./routes/model');
app.use('/model', modelRouter);

I'm very new to node JS and express, might be missing something but can't figure out what.

so far i only get

GET /model/341rtertwert 404

Update

For whoever steps upon this question, there is no correct answer. I tried Sweet Chilliy Pilly answer and it did not work, maybe because I'm using module routes in separate files. However I changed back to the way i had it and tried to access the route through url with some random parameter and it worked. After it worked aswell using axios. I did restart node js several times. In other words, I have no idea why it decided to work now. But it's solved.

1 Answers

You are getting a 404 at this route /model/341rtertwert because you have defined your route to be /:id. In your situation, your router is looking for a route called /model/341rtertwert.

What you likely need to implement is paramed routes: https://expressjs.com/en/guide/routing.html

If you changed your route to be


router.get('/model/:id', function (req, res, next) {
// can't get here


});

then this should work.

Related