what command I should write in ExpressJS file just so that exposes a single HTTP endpoint (/api/search?symbol=$symbol&period=$period)
Working
app.get('/api/search/', (req, res) => {
res.send(req.query)
})
Not working:
app.get('/api/search?symbol=$symbol&period=$period', (req, res) => {
res.send(req.query)
})
app.get('/api/search?symbol=$symbol&period=$period', (req, res) => {
res.send(req.query)
})
In place of this, you have to write below code
const note = require('../app/controllers/note.controller.js');
// Create a new API CALL
app.get('/comment/get', note.index); // In socket.controller.js i have function with the name of index
//note.controller.js file code
exports.index = (req, res) => {
var requestTime = moment().unix();
req.body = req.query;
console.log(req.body); // you will able to get all parameter of GET request in it.
}
Let me know if i need to explain more about
And for sample code of express for API you can view this...
https://github.com/pawansgi92/node-express-rest-api-sample
What I think you're looking for is this:
app.get('/api/search', (req, res) => {
let symbol = req.query.symbol
let period = req.query.period
})
So when you navigate to /api/search?symbol=foo&period=bar
req.query.symbol is "foo"
and req.query.period is "bar"
Related
Running NodeJS on Ubuntu 20.04.2, using VSApp with the debugger
I have the following file named /src/routes/regions.js:
const router = require('express').Router()
const { int } = require('neo4j-driver')
const { required, optional } = require('../middleware/auth')
const { check } = require('express-validator')
const validate = require('../middleware/validate')
const neo4j = require('../neo4j')
const Joi = require('joi');
const Region = require('../entities/Region')
router.get('/1', (req, res, next) => {
return req.neo4j.read(`
MATCH (regions:Region)
return regions order by regions.name ASC
`, params)
.then(regions => res.send(regions))
.catch(e => next(e))
})
router.get('/', (req, res, next) => {
return req.neo4j.read(`
MATCH (regions:Region)
return regions order by regions.name DESC
`, params)
.then(regions => res.send(regions))
.catch(e => next(e))
})
router.get('/:name', (req, res, next) => {
const params = {
name: req.params ? req.params.name : null
}
return req.neo4j.read(`
MATCH (region:Region { name: $name }) return region
`, params)
.then(regions => res.send(regions))
.catch(e => next(e))
})
module.exports = router;
From a browser, if I enter localhost:3000/regions I receive the list of all the Regions in Descending order.
But if I try to enter localhost:3000/regions/1 I receive nothing. The only difference between the two calls should be the order of the received data. The same for localhost:3000/regions/Lazio
It looks like it is not able to recognize patterns in the provided URL
The other really strange behavior is that if I set a breakpoint on any line of the file, the debugger doesn't stop. It looks like it is running another program ....
Can someone help?
Your first route needs to include the name parameter. Express routes aren't inclusive of any others defined elsewhere, so you need to spell it out a bit.
router.get('/:name/1', (req, res, next) => {
I have question about route to get both request from param and body
My route is to delete user. It looks like this:
router.delete("/delete/:id",middleware, async (req, res) => {
//firstly, I get param:
var userId = req.params.id || '';
//if emty, it will get request from body
if(!userId){
const listId = req.userIds
}
});
I perform request but it shows error: Cannot DELETE /api/users/delete
http://localhost:5000/api/users/delete/
Can you explain me what wrong with my issue?
Based on your latest comment you will need a route for collection delete as well as the model route. Here is some "pseudocode":
// model form
router.delete("/delete/:id",middleware, async (req, res) => {
var userId = req.params.id
// made up backend service - add error handling, etc
await dataService.users.delete(userId);
res.sendStatus(200); // again with error stuff
});
// collection form
router.delete("/delete",middleware, async (req, res) => {
var userIds = req.body.userIds; // assumes use of bodyParser
for (userId in userIds) {
// made up backend service - add error handling, etc
await dataService.users.delete(userId);
res.sendStatus(200); // again with error stuff
}
});
I am not sure if this is a Mongoose or Nodejs Express error?
I would just like to know if there is a way to add middleware in the form of an if. This is my call:
app.post(pPath, auth, (req, res) => {
...
})
And I would just like to do something like this:
app.post(pPath, varBoolean ? auth : null, (req, res) => {
...
})
The above example does not work though. Any idea how I can do this?
Express methods don't support non-function handlers. This is generally a good thing because this allows to detect problems with imports on application start.
This can be achieved with a spread:
app.post(...[pPath, varBoolean && auth, (req, res) => {
...
}].filter(Boolean))
You should try using 'app.use', if you want to have a middleware in place.
app.use('/path', (req, res, next) => {
const { test } = req.body;
const { auth } = req.headers;
if(!test) {
return res.status(400).json({message: 'Missing field test'});
}
const validToken = await tokenValidation(auth);
if(!validToken){
return res.status(403).json({message: 'Unauthorized'});
}
next();
});
I wonder how to using path in express dynamically. For example, i'm using lodash for finding a path in different file with regex method.
routes.js
const json = require('./routes.json')
const _ = require('lodash')
routes.use(function(req, res, next) {
let str = req.path
let path = str.split('/')[1]
// [Request] => /test/123
console.log(path)
// [Result] => test
let test = _.find(json.routes, function(item) {
return item.path.match(new RegExp('^/' + path + '*'))
})
console.log(test)
//{"path" : "/test/:id", "target" : "localhost:2018", "message" : "This is Test Response" },
routes.get(test.path, function(req, res) {
res.json("Done")
})
})
On above code, i just nested the routes. But there's nothing any response. Is there any ways to do this? This method also i want to use with DB if necessary. Thanks anyway
Using middleware is impossible. When a request comes, expressjs will search a registered path first.
So here we go why that code not running as well.
For example, I'm as an user request : localhost:2018/test/123
Please following my comment in below
const json = require('./routes.json')
const _ = require('lodash')
routes.use(function(req, res, next) {
let str = req.path
let path = str.split('/')[1]
// [Request] => /test/123
console.log(path)
// [Result] => test
let test = _.find(json.routes, function(item) {
return item.path.match(new RegExp('^/' + path + '*'))
})
console.log(test)
//{"path" : "/test/:id", "target" : "localhost:2018", "message" : "This is Test Response" },
//And now, the routes has been registered by /test/:id.
//But, you never get response because you was hitting the first request and you need a second request for see if that works. But you can't do a second request, this method will reseting again. Correctmeifimwrong
routes.get(test.path, function(req, res) {
res.json("Done")
})
})
How to approach this goal then? However, we need a registering our routes inside app.use or routes.use . So far what i got, we can using loop in here.
//Now, we registering our path into routes.use
_.find(json.routes, function(item) {
routes.use(item.path, function(req, res) {
res.json("Done")
})
})
//The result become
/**
* routes.use('/test:id/', function(req, res, next){
res.json("Done")
})
routes.use('/hi/', function(req, res, next){
res.json("Done")
})
*/
Reference : Building a service API Part 4
Thanks anyway, leave me a comment if there's something wrong with this method :D
I'm trying to send two json but It doesn't work. It prints TypeError: res.json is not a function but I don't get why It happens. Is there any ideas? Thank you !!
app.post('/danger', function response(req, res) {
let placeId = req.body.data;
let option = {
uri: 'https://maps.googleapis.com/maps/api/directions/json?',
qs: {
origin:`place_id:${placeId[0]}`, destination: `place_id:${placeId[1]}`,
language: 'en', mode: 'walking', alternatives: true, key: APIKey
}
};
rp(option)
.then(function(res) {
let dangerRate = dangerTest(JSON.parse(res), riskGrid);
res.json({ data: [res, dangerRate]});
})
.catch(function(err) {
console.error("Failed to get JSON from Google API", err);
})
});
Because you're overwriting your res variable in the .then of your rp function:
app.post('/danger', function response(req, res) { //see, "res" here was being overwritten
..
..
rp(option).then(function(response) { //change the variable name of "res" to "response" (or "turtles", who cares, just dont overwrite your up most "res")
I got this error message because I had the arguments in the wrong order in the handler method. (amateur's fault)
Wrong order: (res, req)
app.get('/json', (res, req) => {
res.json({
"message": "Hello json"
});
});
Right order: (req, res)
app.get('/json', (req, res) => {
res.json({
"message": "Hello json"
});
});
.json isn't a function. Unless you are using a library that makes it one, JavaScript uses JSON (with two methods .parse() and .stringify() one of which you use in the line above).
If you are trying to set an object property by the name of .json then it would be:
res.json = {data: [res, dangerRate]};
With new httpClient libary, you don't need to call .json() method, Just use this simple map instead of the json method.
.map(res => res );
check the sequence=>
If you have write nested res and you write (res,req) you get error.
order plays a very big role in app.get('/',(req,res)=>{ });
you can change the name instead of req and res but the second arg should be of res and the first should be of req
like app.get('/',(a,b)=>{ b.json({});
above syntax is res.json({}) ,we are sending a json file at '/'
const express = require('express');
const path = require("path");
const bodyParser = require('body-parser');
const app = express();
const PORT = 80;
app.use(bodyParser.urlencoded({
extended: false
}));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.post('/api/v1', (req, res) => {
// const userName=req.body.name;
res.send("<h1>done</h1>");
console.log(req.body);
});
app.get("/api/v1/userdata", (req, res) => {
res.json({
name: "your_Name",
email: "your_Email",
password: "hexed",
});
});
app.listen(PORT, () => {
console.log("listening on port 80");
});