I have this angular method that gets features. I only need the features that have the releaseid that I pass with paramters.
getFeatures() {
this.route.params.subscribe(params => {
this.featureService.getFeatures(params['releaseid']).subscribe(res => {
this.features = res;
})
});
}
My service (featureService):
getFeatures(releaseId) {
const uri = 'http://localhost:4000/features';
return this
.http
.get(uri, {params: {releaseId: releaseId}})
.map(res => {
return res;
});
}
My nodejs route
featureRoutes.route('/features').get(function (req, res) {
console.log(req.body.params);
});
But the req.body.params is undefined.
Any help on this?
Try this
Service (featureService):
getFeatures(releaseId) {
const uri = 'http://localhost:4000/features?releaseId=' + releaseId;
return this.http.get(uri);
}
Nodejs route:
featureRoutes.route('/features').get(function (req, res) {
console.log(req.params); // should contain your releaseId
});
You should now be able to get the releaseId in your node backend.
I found it. in my routes i had to do:
console.log(req.query.releaseId)
Related
I have the below route created in my application which calls another API for data:
newsr.get('/news', async (req, res) => {
var category = req.params.category;
try {
var url = 'http://newsapi.org/v2/top-headlines?country=in&category=general' + '&apiKey=36f3e29b704f41339af8439dc1228334';
const news_get = await axios.get(url)
res.status(200).json().render('category', { articles: news_get.data.articles })
// return res.status(200).json(news_get)
} catch (error) {
if (error.response) {
console.log(error)
}
}
})
The problem is, when I call the get API http://localhost:8080/news. I do not get the response from the external API. Can you please suggest what to do?
I'm using MERN stack for a project. I want to hide my api endpoints on the frontend when I call them. I'm now making a request from React like so:
useEffect(() => {
axios
.get("https://MY_API_URL/posts") // MY_API_URL is the url that I want to hide
.then((res) => {
dispatch(setCurrentUser(res.data));
})
.catch((err) => {
console.log(err);
});
});
This is how I'm GETing the posts from the expressjs:
controllers/posts.js
const Post = require("../models/post");
const getPosts = async (req, res) => {
try {
const post = await Post.find();
res.status(200).json(post);
} catch (err) {
res.status(404).json({ message: err });
}
};
I want to make the request to the url from the backend so that my API is hidden in the client.
This is what I have tried in the frontend:
useEffect(() => {
axios
.get("http://localhost:3000/posts")
.then((res) => {
dispatch(setCurrentUser(res.data));
})
.catch((err) => {
console.log(err);
});
});
And my backend now looks like this but it doesn't work. I also have removed the Posts.find() inside the request, I'm not sure if it is still necessary or how am I going to use this?
controllers/posts.js
const getPosts = async (req, res) => {
try {
const response = await axios.get(
"https://MY_API_URL/posts"
);
const posts = response.data;
console.log(posts);
res.status(200).json(posts);
} catch (err) {
res.status(404).json({ message: err });
}
};
On localhost it works fine, but when I push my code to github and deploy it, it doesn't work on the deployed version then in the localhost it also stops working.
Error message on console:
GET http://localhost:3000/posts 404 (Not Found)
it does give me back the id , but it is not deleting it from the mongodb collection & frontend list , I keep getting a 404 error on the network dev tools tab....
NodeJS
app.delete("/showlist-fromdb/:id", async (req, res) => {
try {
let uid = req.params.id.toString();
List.deleteOne({ _id: uid });
} catch (err) {
console.error(err);
}
});
React:
export const deleteListing = async (idHolder) =>{
/**DELETE METHOD */
const options = {
url: `http://localhost:5001/showlist-fromdb/:id${idHolder}`,
method: 'DELETE',
// data: idHolder
};
axios(options)
.then(response => {
console.log('A listing got deleted!')
}).catch((err)=>{console.log(err)})
// axios.delete(`http://localhost:5001/showlist-fromdb/:id${idHolder}`)
}
figured out the problem i forgot to add await before the delete command, thanks everyone
How to understand if somebody requests image or file in express? For example:
https://example.com/image.png
https://example.com/file.js
app.get("/:fileName", (req, res) => {
const file = req.params.fileName.split(".");
const fileExtension = file[file.length-1];
const imageExtensions = ["png", "jpg"];
if(imageExtensions.includes(fileExtension) {
console.log("It's an image");
} else if (fileExtension === "js") {
console.log("It's a javascript file");
}
return res.send();
});
But i would recommend to just separate the routes per resource type, for example:
app.get("/img/:fileName", (req, res) => {
console.log(`Getting image ${req.params.fileName}`);
return res.send();
});
app.get("/js/:fileName", (req, res) => {
console.log(`Getting JS file ${req.params.fileName}`);
return res.send();
});
Once the server received the request, you can check for the extension of the url and later process it. [need more information to know exactly what you need]
I am trying to use node-http-proxy inside an AdonisJS controller, but I get the error
The "url" argument must be of type string. Received type function
The line causing the error is the proxy.web(request, response, { target: urlToProxy });
async proxy({ request, response }){
var resource = await Resource.query().where('uri', request.url()).with('service.user').with('userSecurity').first()
resource = resource.toJSON()
if(!resource.service.active){
return response.status(404).send(`Parent service '${resource.service.title}' is disabled`)
}
if(!resource.active){
return response.status(404).send(`Resource is disabled`)
}
if(resource.userSecurity.length <= 0) {
return response.status(403).send(`You are not permitted to access that resource. Contact ${resource.service.user.first_name} ${resource.service.user.last_name} (${resource.service.user.email})`)
}
var urlToProxy = url.resolve(resource.service.basepath, request.originalUrl())
var proxy = httpProxy.createProxyServer()
proxy.web(request, response, { target: urlToProxy });
}
In the end I got a bit closer but not a full fix. The getting close bit was to realise the http-proxy was delivering data via buffer so I had to do something like this
proxy.web(req, res, { target: data.service.basepath})
proxy.on('error', function(err, req, res){
console.log("There was an error", err)
})
proxy.on('proxyRes', async (proxyRes, request, response) =>{
var body = new Buffer('')
proxyRes.on('data', (data)=>{
body = Buffer.concat([body, data])
})
proxyRes.on('end', ()=>{
body = body.toString()
try{
res.send(body)
}catch(err){
}
})
});
However, I still could not get it to work as the controller was returning before http-proxy had completed the request.
In the end and probably for the best, I wrote a stand alone proxy app and used the main app just to validate JWT tokens before they go through the Proxy.
You were so close, I wanted to do something similar and wrapped the proxy in a promise so we can wait for the proxy to return before responding with our response:
const proxy = httpProxy.createProxyServer();
const prom = new Promise((resolve, reject) => {
proxy.web(request.request, response.response, {
target: urlToTarget
}, (e) => {
reject(e);
});
proxy.on('proxyRes', function (proxyRes, req, res) {
let body = [];
proxyRes.on('data', function (chunk) {
body.push(chunk);
});
proxyRes.on('end', function () {
body = Buffer.concat(body).toString();
resolve(body);
});
});
});
const result = await prom;
response.body(result);
return response;
I thought I'd give you a complete answer for anyone else that comes across this.