I am new to this node.js. I am using mysql in my node.js. From the url i am constructing sql query. With 1 parameter its working fine.
The URL:
http://ipaddress:3002/users/Kappalur
By using the following code i extracted the Kappalur and its working fine:
app.get('/users/:level', function (req, res) {
connection.query("select * from levels where level4= '"+req.params.level+"'", function(err, rows, fields) {
res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(rows,null,"\n"));
Now my requirement is i want to make "level4" to be dynamic..
Consider now the url be:
http://ipaddress:3002/users/level4/Kappalur
Now how can i change the above code to get the 2 parameters from url. Help me to solve this..Thanks in advance.
As I understood you are using express framework for node.js.
To retrieve multiple URL parameters use just the same pattern as that you have used in your post's code snippet:
app.get('/users/:level/:name', function (req, res) {
var level = req.params.level;
var name = req.params.name;
Related
I want to make an route with multiple parameters using Node Express MySQL. Is it possible to do this with traditional url parameters like: page?id=2&user=10
Here is a simple query, but the only way of doing it so far is like this: page/2/10
app.get("/get-page/:id/:user", function (req, res) {
let sql = "SELECT * FROM table WHERE id= '${req.params.id}' AND userid= '${req.params.user}'`;";
let query = db.query(sql, (err, results) => {
if (err) throw err;
res.send(results);
});
});
This is just an example.
The reason I would like the traditional way is because, with the "slash" method the parameters always have to come in the correct order, or did I miss something?
Perhaps use the query property of the request to access the query string, as in req.query.id:
app.get("/get-page", function (req, res) {
console.log('ID: ' + req.query.id)
});
I have an API written in express. I am trying to add a simple endpoint with a pretty straightforward query that runs correctly in the MySQL terminal. However, when I pass the query my parameters (start and end dates), the query doesn't work when I send a GET request using Postman. This is where my query is in my API:
var db = require('../../dbconnection');
var PORegister = {
getPORegister:function(start,end,callback) {
return db.query("SELECT * FROM purchase_orders WHERE PODate BETWEEN '?' AND '?' ORDER BY PODate DESC",[start,end],callback);
}
}
module.exports = PORegister;
And here is my routing in Express:
var express = require('express');
var router = express.Router();
var PORegister = require('../../models/reports/PORegister');
router.get('/:start/:end',(req,res,next) => {
PORegister.getPORegister(req.params.start,req.params.end,(err,rows) => {
if (err) res.json(err);
else res.json(rows);
})
})
module.exports = router;
I have console logged in the routing file and I know that my req.params are coming in formatted as I wish, (YYYY-MM-DD), this is the format which has worked in MySQL for me. Something is going wrong when I pass these parameters into the query and I do not understand what it is.
I'm trying to retrieve data from a SQL database and display that said data on a Reactjs web app. However, all the calls I make to the database results in the HTML of the webpage in focus. I have set the headers, and I've tried to change the way the response from the express call is being handled.
Here is the expressjs script I am using right now:
const express = require('express');
const sql = require('mssql/msnodesqlv8');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const db = require('./db.js');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/counselling/triageadmin/', express.static(path.join(__dirname, '/build')));
app.use(cors());
app.get('/getTable', function (req, res, next){
var request = new sql.Request(db);
request.query('select * from Counselling order by TicketID desc', (err, result) =>{
if (err) { return next(err); }
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(result["recordset"]));
});
});
From there, my axios calls look like this:
componentWillMount(){
let self = this;
axios.get("/getTable")
.then(function (response){
console.log(response.data);
self.setState({
data: response.data,
});
})
.catch(function (error){
console.log(error);
})
}
I added the console.log to check what was being returned, and as said, it was the HTML code of the current page of focus.
I made some changes to reflect what steps I took to get the 500 issue out. The current code, however, results in a 404.
If you move your get on top of your put it should work. The problem seems to be that the static clause resolves your request before it gets to your endpoint, so if you do this:
app.get('/counselling/triageadmin/getTable', function (req, res, next){
var request = new sql.Request(db);
request.query('select * from Counselling order by TicketID desc', (err, result) =>{
if (err) { return next(err); }
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(result["recordset"]));
});
});
app.use('/counselling/triageadmin/', express.static(path.join(__dirname, '/build')));
the path to the get will attempt to be matched before you're routed to your static files.
Ideally you would want to have your rest endpoints under a different namespace, i.e. /api but if you decide to keep your setup, this should help.
I think your routes might be conflicting with each other. From the express documentation at: http://expressjs.com/en/4x/api.html#app.use
// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
res.send('Hello World');
});
// requests will never reach this route
app.get('/', function (req, res) {
res.send('Welcome');
});
Thus, your route '/counselling/triageadmin/getTable' will never be reached, because your route '/counselling/triageadmin/' is intercepting it, responding with static resources.
To solve this, try organizing your routes in a way that puts all of your API requests at a different subfolder, like '/api'. So your getTable endpoint would be located at: '/api/counselling/triageadmin/getTable/' or something like that.
I'm also learning the MEAN stack and I stumbled upon your question since I had the opposite problem. I wanted it to respond with an HTML instead of a JSON
this line of code MAKES it respond with an HTML
res.send(JSON.stringify(result["recordset"]));
(I tried res.send("<h3 HTML T_T </h3>");) and it did send and HTML
however, if you try
res.json(String(req.params.id)); <= Notice the res.json instead of res.send
It responds with a JSON :)
I hope this helped
I'm building a web site using node.js express MySQL and boostrap, when I try to send a variable against method get for to do a query to the database, it's seem doesn't work, because there's no a good render. this is my code:
app.get('/reservaciones/leer/:id', function(req, res) {
var idreservacion = req.params.idreservacion;
crud.get_leer_reservacion(req,idreservacion,function(data_leer){
res.render'../views/leer.html',data:data_leer});
});
});
exports.get_leer_reservacion = function(req,idreservacion,fn){
// here the query
connection.query('select * from reservacion where idreservacion = '"+idreservacion+"'', function(err,rows){
if(err){
throw err;
}
return fn(rows);
});
};
https://drive.google.com/folderview?id=0BxFTEy90zOKAfmJOXzR3NDFLa081NUtEUFU4LWhuN2ZUTDMtVktPeHlYbVUzWW02a2pGWEk&usp=sharing
res.render'../views/leer.html',data:data_leer});
should be:
(outside of app.get:)
app.use('views', '../views');
(inside:)
res.render('leer',{data:data_leer});
If your problem is actually getting the templated data into the page I suggest the ejs npm package and templating system, you would use <%= data => to template in the value
In this code:
app.get('/reservaciones/leer/:id', function(req, res) {
var idreservacion = req.params.idreservacion;
You define a parameter called id, but you retrieve a parameter called idreservacion. Try something like this:
app.get('/reservaciones/leer/:id', function(req, res) {
var idreservacion = req.params.id;
I am new to this node.js concepts.What i have tried is updating a database and retreiving datas from database(working fine).On further step i returned the output(from database) into an "JSON" format(working fine)..Now my requirement is to have a dynamic query..
Consider:
The following url:
http://xxx.xxx.xx.x:3002/users will retrieve all datas from users table and return in json format
But what i want is:
http://xxx.xxx.xx.x:3002/users=abcdef so the datas for that particular user should be returned in json format.
My code:
app.get('/users', function (req, res) {
connection.query('select * from nodejs where', function(err, rows, fields) {
res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(rows));
//res.render('users', {users: docs});
});
});
So how can i modify the above code to retrieve only for specific users details..Help me to solve this..Thanks in advance..
Create a new route in your application. You can specify parameters in your URL as
http://xxx.xxx.xx.x:3002/users/fname1
Here fname1 is user Id and you can add the following code to get the parameter from url
req.params.fname
Here the fname is got the name from the route that defined in your application as:
app.get('/users/:fname', function (req, res) {
connection.query("select * from nodejs where fname= '"+req.params.fname+"'", function(err, rows, fields) {
res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(rows));
//res.render('users', {users: docs});
});
});
Use url/:nameOfParameter to specify the name for values in url