Express - Get response from one url to another - node.js

I have a post methon that calculate some thing and return it with the res.json method.
The code look something like this:
app.post("/calc", function (req, res) {
res.json({result: 100});
});
I want to get that JSON from another post method, like that:
app.post("/useCalc", function (req, res) {
let json = // Call "/calc" somehow...
console.log(json) // print {result: 100}
res.end();
});
How can I do it? Thank you!

One workable approach is using a 307, https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect#99966.
Another way I would suggest is to create a common method to handle them two.

Related

Axios - send get request with url + variable

This must be a stupid question, but I'm just starting and would appreciate any help!
So I have this code to get query parameter:
app.get('/', (req, res) => {
var code = req.query.code;
console.log(code);
And when I go to http://localhost:3000/?code=123, I get the code value in console, so it works fine.
Now, I need to send a GET request and add the value of the var code, this is where I'm stuck.
Let's say, I should send a GET request to 'http://testtesttest123.com/' + var code + 'hi'.
How can I do this?
I've tried this way and some other ways, but nothing worked:
axios.get('http://testtesttest123.com/?&code=', {params: {code}}, '&hi')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
});
Thank you in advance!
The axios.get call should look like this.
axios.get('http://testtesttest123.com/?code=' + code + '&hi')
With code = 123, this will call the URL http://testtesttest123.com/?code=123&hi.
Use the params config to send through query parameters. To support your empty hi parameter, you can include it in the URL string
axios.get("http://testtesttest123.com/?hi", {
params: { code }
})
For a code value of 123, this will perform a GET request to
http://testtesttest123.com/?hi&code=123
It will also ensure that the code value is made safe for use in URLs

Transforming a payload from requestjs before sending it to the client

Brothers and sisters, I am building an Express API Endpoint that needs to consume an external API, perform some changing of keys and values, and return to the result to the client. Here is what I have thus far:
const external_endpoint = <external_api_end_point>;
app.get('/', function (req, res, next) {
request({ url: external_endpoint}).pipe(res);
});
This returns the exact payload you would get from hitting the external_endpoint directly.
Isn't there something I can do to change res before it gets sent to the client? I tried a few things but nothings has worked. Any ideas or best practices associated with doing a transform on the incoming payload?
For the sake of simplicity. Lets say this is the payload obj.json:
{
"sad": {
"userid": 5,
"username": "jsmith",
"isAdmin": true
}
}
and I am wanting to change sad to happy.
I know outside of the request I could do something like this:
obj = JSON.parse(JSON.stringify(obj).split('"sad":').join('"happy":'));
but throwing obj in place of res will not work. I have tried assigning the value of this res and res.body but no dice.
Thanks for you help in advance!
If you're using request-promise, you can simply make a new response and send it, or modify the response you got back:
app.get('/', function (req, res, next) {
request({ url: external_endpoint, json: true})
.then(response => res.json({ happy: response.sad })))
.catch(next);
});
(of course, you need to handle errors appropriately)
If you want to process it as a stream (which makes sense if you have a massive amount of data), you can use the original request module, and use event-stream to create your pipe:
const es = require('event-stream');
const swapper = es.through(
function write(data) {
this.emit("data", data.replace("sad", "happy"));
},
function end() {
this.emit("end");
}
);
request({ url: external_endpoint})
.pipe(es.stringify())
.pipe(swapper)
.pipe(es.parse())
.pipe(res);
Here's a sandbox to test the stream processing: https://codesandbox.io/s/3wqx67pq6

How to put objects dynamically in res.render

How can I get an object dynamically in res.render in express in a MEAN stack?
res.render('myTemplate', {title: 'This is my title'});
I want something like this:
res.render('myTemplate', function(){
var myReturnObject{title: 'This is my title'};
//do someting to generate return object;
return myReturnObject;
});
Can anyone advise how can I generate my template variables programmatically in render function?
Thanks.
You can put your data into an object and then pass it in the res.render.
var myReturnObject = {title: 'This is my title'};
res.render('myTemplate', myReturnObject);
Your res.render() calls will live in the context of a controller. For example , it could be something like (app.get('/', function(req, res) {});. Typically, you would want to fetch some data, then pass the fetched data to the template in your res.render() callback. The snippet below show how you would do this with a fictitious callToDb() function that query a database:
app.get('/', function(req, res) {
callToDB(function(err, results) {
const templateVars = {//use results like you want here};
res.render('path/to/template/, templateVars);
});
});

Express router "res" object has to take me to other pages

See the example below:
var apiRouter = express.Router();
apiRouter.post('/api/postAgree', function(req, res, next){
userModel.findOneAndUpdate(
{profileID: req.session.facebookProfileId},
{$push:{postsAgreed: req.query.postID}},
{safe: true, upsert: true},
function(err, model) {
if (err){
console.log(err);
}
}
)
Now, the MongoDB operation is already done and I want to stay on the same page.
Will I be doing this:
res.render('theSamePageIamOn', {foo:bar});
I know this works but it seems like it is a very inefficient way of doing it.
So my question really is: If I have a button on a page which makes an API call but I want to stay on the same page, how will I do that? The res.(options) function sort of is made like it has to take me to other pages
Thanks to #robertklep and #GiladArtzi - it should be an AJAX call and the response should be in the form of:
res.json()
Then the response can be handled by the frontend using other tools like: Angular
I'm not sure what you're talking about, just call the function....
function doesSomething (args) {
console.log(args)
}
apiRouter.post('/api/postAgree', function(req, res, next){
doesSomething("HELLO")
});
Function calls don't expects the user to go to another page each time an API call is handled.

writing node.js get handler with parameters?

How do I write a get handler for the following URL with node.js?
http://localhost:3000/auth?code=xxxxxxx
The following code did not work
app.get('/auth', function (req,res) {
});
It's not working because it doesn't do anything. You need to send a response:
app.get('/auth', function (req,res) {
res.send('Hi it worked. Code: ' + req.query.code);
});
Another way to do it would be like this:
app.get('/auth/:code', function (req,res) {
res.send('Hi it worked. Code: ' + req.params.code);
});
and the URL would simply be http://localhost:3000/auth/xxxxxxx
Please note that, some client sides should accept a certain response type.
For instance, you should send a JSON object as a response.
So, rather than just responding a string, it is better if you send a JSON object as:
app.get('/auth', function (req,res) {
res.send({ 'response' : 'Hi it worked.', 'code': req.query.code });
});

Resources