I'm trying to use query parameters in a get request in Express, but there are no parameters in the request body
On the frontend
query () {
if (window.location.href === 'http://localhost:3000/profile') {
window.location.href = `?contributer=${localStorage.getItem('username')}`;
}
fetch('http://localhost:3002/get-user-recipes')
.then(response => response.json())
.then(data => {
this.setState({
apiResponse: data
});
});
}
and on the backend
app.get('/get-user-recipes', (req, res, next) => {
console.log(req.query); // returns {}
});
Ok I figured it out. The parameters need to go in the express path, so the correct code is
fetch(http://localhost:3002/get-user-recipes?contributer=${localStorage.getItem('username')})
Query Params are usually at the end of a url and are initiated with a ?
Example:
// On the frontend
Making a get request to say :
http://localhost:3002/get-user-recipes?one=1&two=2
The query Params here are one with value of '1' and two with a value of '2'
// On the backend
app.get('/get-user-recipes', (req, res, next) => {
console.log(req.query); // would return { one: '1', two: ,'2' }
});
Related
I have sent data from frontend to backend when I console what type of requests I have gotten I can see the data is showing into the console but when I try to access those properties I got undefined. I have also tried with a query, body but both get undefined when I try to access the property.
Backend code:
// DELETE SHORT URL
app.delete('/delete/:shortUrl', async (res, req) => {
console.log(req);
console.log(req.params, 'req.params');
})
Frontend:
// DELETE
const deleteUrl = (id) => {
fetch(`http://localhost:5000/delete/${id}`, {
method: 'DELETE'
}).then(res => res.json())
.then(data => {
console.log(data);
if (data.deletedCount) {
alert('Order Deleted')
// const remainingOrders = orders.filter(order => order._id !== id)
// setOrders(remainingOrders)
}
})
.finally(() => setLoadings(false))
}
Based on the Express documentation, the route callback's parameters (req & res) are reversed, so you should have:
app.delete('/delete/:shortUrl', (req, res) => {
console.log(req);
console.log(req.params, 'req.params');
})
I am new to Express.
I am creating a new API endpoint, which is getting data from two other publically available endpoints. Once I get the JSON from both APIs, I will merge them according to some rules.
let result1, result2;
// API 1
let data1;
app.get("/test1", (req, res, next) => {
axios.get("https://www.EXAMPLE.com/api/endpoint_A")
.then((response) => {
res.json(response.data)
data1 = response.data;
});
});
// API 2
let data2;
app.get("/test2", (req, res, next) => {
axios.get("https://www.EXAMPLE.com/api/endpoint_B")
.then((response) => {
res.json(response.data)
data2 = response.data;
});
});
console.log(data1); //output is undefined
console.log(data2); //output is undefined
I can see result of successful calls in both the browser and in Postman.
My problem is, that I cannot find a way to manipulate the result of each endpoint. I have tried to store like this result1 = response.data in the then but it is undefined. Once I can access the output of each response, then I have to merge them. But accessing the results outside the axios call appears to be more difficult. I don't have to use axios.
I also tried this but it didn't work.
// API 1
const data1 = app.get("/test1", (req, res, next) => {
axios.get("https://www.EXAMPLE.com/api/endpoint_A")
.then((response) => res.json(response.data));
});
console.log(data1); //output is undefined
as far as im aware data does not persist between api calls. you could combine that into a single endpoint.
//Both apis into one endpoint
app.get('/test', (req, res, next) => {
const promiseArr = [axios.get('https://www.EXAMPLE.com/api/endpoint_A'),
axios.get('https://www.EXAMPLE.com/api/endpoint_B')];
Promise.all(promiseArr).then(responses => {
const resultsFromEndpointA = responses[0];
const resultsFromEndpointB = responses[1];
//do what you want with your results here... for example..
return res.status(200).json({resultsFromEndpointA, resultsFromEndpointB});
//or do something like load them into a session
req.session.results = {resultsFromEndpointA, resultsFromEndpointB};
next();
}).catch(err => {
console.log(err);
});
};
If you are getting an array of objects with the same properties from the both endpoints, do this;
let results = [];
// API 1
app.get("/test1", (req, res, next) => {
axios
.get(
"https://www.EXAMPLE.com/api/endpoint_A"
)
.then((response) => {
results.push(response.data);
});
});
// API 2
app.get("/test2", (req, res, next) => {
axios
.get(
"https://www.EXAMPLE.com/api/endpoint_B"
)
.then((response) => {
results.push(response.data);
});
});
I am trying to obtain json files with axios' GET request, but the information is not retrieved.
In index.js (retrieving information):
axios.get('http://localhost:1000/getpost/')
.then((response) => {
console.log(response);
});
Backend endpoint getpost.js (sending information):
var router = require('express').Router();
var Posts = require('../models/post-model.js');
router.route('/').get(() => {
Posts.find({color: "Green"})
.then((res) => {
return res;
});
});
module.exports = router;
I have also tried return Posts.find({color: "Green"}); inside the router.route('/').get... function,
but the value returned is different compared to the one in the promise which is the one I need. I checked that the information is actually sent with console.log(res), but it is not received in the frontend--when I log the result there, it is null.
You are not doing anything with the route response. Maybe something like...
router.route('/').get((req, res1) => {
Posts.find({color: "Green"})
.then((res) => {
res1.end(res);
});
});
(assuming res is the data in plaint text, if it is a JavaScript object you'll do res1.json(res) or res1.jsonp(res))
You need to map the route to getpost as:
router.route('/getpost')
So your getpost would be as:
var router = require('express').Router();
var Posts = require('../models/post-model.js');
router.route('/getpost').get(() => {
Posts.find({color: "Green"})
.then((res) => {
res.send({status:200,message:res});
});
});
module.exports = router;
Apparently, I was not passing the result properly.
The router in getpost.js should be:
router.route('/').get((req, res) => {
Posts.find({color: "Green"})
.then((posts) => res.json(posts));
});
I want to show message after deleting user but I don't know how to do it. I tried to create req.session properties and then use them but they are not available in GET route. Do you know how to fix this code?
router.get("/", mid.isExpired, mid.isLoggedIn, mid.isAdmin, (req, res) => {
let currentMessage = req.session.message;
let currentState = req.session.state;
req.session.message = undefined;
req.session.state = undefined;
console.log(currentState, currentMessage); //undefined
user.getAll()
.then(result => {
res.render("users", {
name: req.user,
users: result,
msg: currentMessage,
state: currentState
})
})
});
// delete route
router.delete("/delete/:id", mid.isExpired, mid.isLoggedIn, mid.isAdmin, (req, res) => {
user.del(req.params.id)
.then(() => {
req.session.message = "Some message!"
req.session.state = true;
})
});
// jquery
function ajaxDelete(ev, url) {
ev.preventDefault();
$.ajax({
url: url,
type: "DELETE"
});
}
delBtn.click(function(e) {
var user = $(this).data("user");
ajaxDelete(e, "/users/delete/" + user);
window.location.href = "/users";
})
Use res parameter, and make a variable called message
const message= 'MyMessage';
then
res.json ({message}) // es6 feature
output
{"message":"myMessage"}
In your scenario, as far as I understand you want to send the JSON in response. You can use this code
router.delete("/delete/:id", mid.isExpired, mid.isLoggedIn, mid.isAdmin, (req, res) => {
user.del(req.params.id)
.then(() => {
var response = { message : "Some message!",
state : true };
return res.json(response);
})
});
the keyword 'return' is as per your requirement
router and session are middleware to any nodeJs App,If the router is added before session like this:
app.use(router)
app.use(session(...));
Then the session middleware won't get called for any requests that get handled by router.
Hence change the order of adding router and session middleware,like this
app.use(session(...));
app.use(router)
I want to display the json i got from the search for localhost:8400/api/v1/search. But I have no idea how.
I'm using the Elasticsearch Javascript Client
my routing:
'use-strict';
const express = require('express');
const elasticsearch = require('../models/elasticsearch.js');
const router = express.Router();
router.get('/api/v1/search', elasticsearch.search);
for accessing the ElasticSearch DB
const es = require('elasticsearch');
let esClient = new es.Client({
host: 'localhost:9200',
log: 'info',
apiVersion: '5.3',
requestTimeout: 30000
})
let indexName = "randomindex";
const elasticsearch = {
search() {
return esClient.search({
index: indexName,
q: "test"
})
.then(() => {
console.log(JSON.stringify(body));
// here I want to return a Response with the Content of the body
})
.catch((error) => { console.trace(error.message); });
}
}
module.exports = elasticsearch;
Firstly, the route handlers for express routes always have (request, response, next) as it's parameters. You can use the response object to send data back to the client.
Instead of passing the elasticsearch.search method as a route handler, you can write your own route handler and call elasticsearch.search in there, so you still have access to the response object. For example:
function handleSearch(req, res, next) {
elasticsearch.search()
.then(function(data) {
res.json(data)
})
.catch(next)
}
And structure your search function like so:
const elasticsearch = {
search() {
return esClient.search({
index: indexName,
q: "test"
})
.then((body) => body) // just return the body from this method
}
}
This way you separate your concerns of querying elastic and handling the request. You also have access to the request object in case you want to pass any query string parameters from your request to your search function.
Since you add elasticsearch.search as the route handler, it will be invoked with some arguments.
Change the signature of the search method to search(req, res).
Then just call res.send(JSON.stringify(body));
See https://expressjs.com/en/4x/api.html#res for more details