Search code examples
node.jsapirestful-url

Why my restful API stuck when I put integer as parameter in the url using node.js


I'm trying to get data in JSON format. I just copied an old project and changed it IP address to database, username, port, password and database name.

When I try to access data through this addres: localhost:3000/&id=13

The browser just doesn't load them.

When I enter the address with the port without / I see the message with error:

return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})

The same code is pinned to another database and I see the data in JSON format.

I checked 10 times if the username, password, port and database name are correct and they are fine.

The code:

    // Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')

app.use(cors())

// Server port
var HTTP_PORT = 3000

var pool = mysql.createPool({
  connectionLimit: 10,
  host: '192.168.0.1',
  user: 'user',
  port: '3388',
  password: 'password',
  database: 'databasename'
});

var ardaforecast = '';


app.route('/')
  .get(function (req, res) {
    // omitted
    res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
    //const date = req.query.date;
    const id = req.query.id;

    pool.query(`CALL Get_Alert_levels_Station(${id})`, function (error, result) {
      if (error)
      return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})
      aladinModel = result;
      res.json({ ardaforecast })
    });
  });

// Start server
app.listen(HTTP_PORT, () => {
  console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});

pool.on('error', function (err) {
  console.log(err.code); // 'ER_BAD_DB_ERROR'
});

app.use(function (req, res) {
  res.status(404);
})

;

Can I get an example of how I can fix this or how to find out where the problem is ?


Solution

  • You can use this one to see how what your url contains: https://www.freeformatter.com/url-parser-query-string-splitter.html

    In your example, the problem is that you're using & (ampersand), but what it does is separating multiple query parameters. Since you have just one, your url is not properly structured and does not contain any parameters whatsoever.

    You should use ? (question mark) to denote the first one:

    localhost:3000/?id=13

    p.s. Успех ;)