Axios - send get request with url + variable - node.js

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

Related

How can I call an API different endpoints by calling my loadApi function every time I need to add a new end point? I'm using axios for my request

I'm working with an API and I'd like to know how to send a request to multiple end points by calling my "Load Api " function every time I need to work with a different end point.
Here's my code with some examples to illustrate what I'm trying to do:
app.get("/", async (req, res) => {
let test = await loadData();
res.render("index", { title: "Home", data: test });
});
// Axios Request to Coin Market Cap Web API
async function loadData(limit) {
let baseUrl = 'https://pro-api.coinmarketcap.com/';
let response = await axios.get( baseUrl + 'v1/cryptocurrency/map', {
headers: {
'X-CMC_PRO_API_KEY': process.env.CMC_PRO_API_KEY,
},
});
// success
return await response.data;
};
On this part baseUrl + 'v1/cryptocurrency/map' I though I'd be able to pass a param to loadData e.g. endPoint and concatenate it with base url.
After that, I'd assign an actual end point to the endPoint value when calling the function:
let test = await loadData('example/endpoint/abc');
Can anyone of you help me with a solution for that?
Cheers!
NVM!
My logic was correct. I was just using an invalid end point/no longer working.
Thanks anyway!

how to repeat get request every values change

I have codes like
app.post('/zamansecimi',(req,res)=>{
{
zamansecimim(req.body.baslangic,req.body.bitis)
res.render('./dist/rapor.ejs')
}});
function zamansecimim (bas,bit) {
app.get("/zamansecimi2", function (req, res) {
data2="select * from raporlama where oncekizaman between $1 and $2"
var query = connection2.query(data2,[bas,bit] ,
function(err, result) {
if(err) throw err;
res.send(httpResponse(result.rows));
});
})
}
In these codes I want to change get result every post request but I have a problem with get request these values never change when I send to 2 or 3 ...request. First request is working.
Where is my mistake?
thank you for your help
Each request sent to the server can only have one response, and you can't trigger a GET request inside a POST request on the server and expect the response to that request to go back to the browser. Without the whole app, I can't tell you the best way to do what you want, but I'd suggest you have one response on the server like this:
app.post('/zamansecimi',(req, res)=>{
const bas = req.body.baslangic;
const bit = req.body.bitis;
const query="select * from raporlama where oncekizaman between $1 and $2";
connection2.query(query,[bas,bit], function(err, result) {
if(err) throw err;
res.send(httpResponse(result.rows));
});
});
That will at least ensure you get the correct data back to the browser. It does not seem to me like rapor.ejs needs re-rendering since nothing has changed on the server with the POST request. But honestly I can't tell what's going on from the code provided.

Express - Get response from one url to another

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.

Cannot GET from Express.js PUT route, why?

Is there any reason you cannot execute a GET request from inside an Express.js router.put()?
I have two routes. The exact same api call works in a router.get() route and hangs in the router.put().
I've confirmed that
This works:
router.get('/:id', async (req, res) => {
const { headers } = req;
let result;
try {
result = await axios({ method:'get', url: '/some-url', headers });
} catch(error) {
res.status(500).send(new Error('myError');
}
res.send({ result });
});
This does NOT work:
router.put('/:id', async (req, res) => {
const { headers } = req;
let result;
let finalResult;
try {
result = await axios({ method:'get', url: '/some-url', headers });
} catch(error) {
res.status(500).send(new Error('myError');
}
// logic based on the result of the above GET determines what the value of `finalResult`
finalResult = { some: 'data' };
res.send({ finalResult });
});
Even though axios({ method:'get', url: '/some-url' }) is the exact same in both routes, it works in one and not the other.
The router.put() route always hangs for a long time and eventually Node outputs:
Error: socket hang up, code: 'ECONNRESET', etc...
Appreciate any help, I've spent over a day scratching my head over this.
No there's no such thing in express. Try hitting the GET request from postman or curl and see if response is coming. The root cause could be an invalid get request you're trying to make or that server on which you are making GET request could be down. You can run following to validate
app.put('/',async (req, res) => {
let response = await axios.get('https://google.co.in');
console.log(response.data);
res.send({"works": "hello"});
});
Root cause of my problem:
The http Headers had a key of Content-Length that prevented GET calls to resolve correctly.
Since these api calls occurred within a router.put() callback, the Headers had a Content-Length pointing to the size of the payload "body" that was being PUT to begin with.
Solution:
Remove that Content-Length field from my Headers when doing GETs inside router.put(), such that the GET has all the other Headers data except for Content-Length
Unfortunately, NodeJS just threw that Error: socket hang up message that was not very descriptive of the underlying problem.

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