Nodejs - HTTP - with optional parameter - node.js

I need to make a http call within my node server .The optional parameter is:
'name='
This means that url (relative path) should look like:
/v1/clans?name=**exampleValue**
So far the options for my http request looks like:
app.get('/v1/:clans?=:name', (req, res) => {
console.log(req.path)
const options = {
host: 'api.clashofclans.com',
path: req.path,
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer *token*'
}
};
const x = https.get(options, (request) => {...});
But that doesnt work out. Does someone know how to include the optional parameters in my path property?

You don't. That's not a parameter you're thinking of. That's a query parameter and your path should look like this:
'/v1/clans
You retrieve the query parameter using req.query.<parameter> in your case req.query.name
The optional url parameter you're thinking of would be like this /v1/clans/:name and would be accessible using req.params.name.

Related

How to pass two parameters to an API 'Get' Request in Javascript/NodeJS

I have a React component that has to do a find({}) query with two parameters to a MongoDB database.
const likes = await Likes.find({ postId: postId, userId: userId }).exec()
As Mongo code only works on the server I have to make an API call (I'm using NextJS). This API call is obviously a GET request. How do I pass 'postId' and 'userId' to the get request using SWR (or fetch)?
I was trying to pass them as an object through the 'body' but I don't think this is the correct way at all.
const likesPerUser = {
postId: postId,
userId: userId
}
const docs = await fetch('/api/likes/user', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(likesPerUser),
})
I don't have access to the URL query string
I have a feeling I may be way off key here. Any help would be very much appreciated.
Cheers,
Matt
Solution with Query Params
You can pass your parameters as query params in your GET request URL.
Here is the format of a URL that has multiple query params:
http://localhost:8000/api/likes/user?postId=xyz&userId=123
Here, you can see the ? symbol which indicates that query params have been started. And, you'll also notice & used for separating multiple query params. This way, you can send as much as query params you want.
Note: All query params are string. Query params size can be maximum 1024 characters in your URL.
Here is a sample code for receiving query params from the node.js backend:
exports.sampleFunction = async (req, res) => {
const postId = req.query.postId
const userId = req.query.userId
// write your code here
}
Here is a sample code for sending the query params from the front-end using fetch:
const docs = await fetch(`/api/likes/user?postId=${postId}&userId=${userId}`, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
let options = {
method: 'GET',
headers: {accept: 'application/json', 'content-type': 'application/json'},
body: JSON.stringify({
your data parameters
}), };
fetch('url link', options)
.then(response => response.json();)
.then(response_json => {
console.log(response_json);
})
OR also set query parameter in your url like this.
http://localhost:8000/test_data?postId=xyz&userId=123

How to parse querystring parameter from URL in Fastify server?

I am a totally new to fastify but I have a fastify server running. I want to parse query string such as:
http://fake.com/?user=123&name=ali
I want to get "user" and "name" values from the URL above. My current code is like this:
fastify.route({
method: 'GET',
url: '/',
handler: async (request, reply) => getCompanyUsers(request, reply, services)
});
I want to get values of "user" and "name" and then pass the values to getCompanyUsers function.
Any help is appreciated.
Thanks
You can access the querystring using request.query
You can look at the official documentation here
https://github.com/fastify/fastify/blob/main/docs/Reference/Request.md
fastify.route({
method: 'GET',
url: '/',
schema: {
// request needs to have a querystring with a `name` parameter
querystring: {
name: { type: 'string' }
}
},
handler: async (request, reply) => {
// here you will get request.query if your schema validate
}
})

NodeJS request library how to get the full URL including URI and query string params

How does one extract/find the full URL from a HTTP request performed with the NodeJS request library. This would be useful for logging purposes.
Here's a code example to demonstrate:
request({
baseUrl: 'https://foo.bar',
url: '/foobar',
qs: {
page: 1,
pagesize: 25
}
}, (err, res, body) => {
// Somewhere here I'd expect to find the full url from one of the parameters above
// Expected output: https://foo.bar/foobar?page=1&pagesize=25
console.log(res);
});
I can't seem to find any properties of the res param in the callback that contains the URL.
To clarify: by full URL I mean the URL constructed by the request library which should include the following fields:
Base URL (or just URI/URL when no base URL was set)
URL (or URI)
Query string parameters
Actually you can easily do that with store your request when you create it.
const request = require('request');
const myReq = request({
baseUrl: 'https://foo.bar',
url: '/foobar',
qs: {
page: 1,
pagesize: 25
}
}, (err, res, body) => {
console.log(myReq.host); // BASE URL
console.log(myReq.href); // Request url with params
});

NodeJS - Request module - GET XML

I am currently trying to get a XML from an external source using request / request-promise.
I did the following:
const request = require('request-promise');
const options = {
method: 'GET',
uri: '',
headers: {
'Content-Type': 'application/xml; charset=utf-8',
},
};
request(options).then((response) => {
console.log(response);
});
The external XML contains characters like ü,ö,ä. They are all missing and are replaced by a question mark in a box.
I thought setting the header would be enough and my google research didn't bring up any other solutions for this scenario.
Am I missing something obvious?
Thanks for every hint!!

Which is the structure of the path in the case of query request?

I'm using hapi.js but one thing is not clear for me. In the case I make api request passing params in the path, I could get these ones by calling request.params in the handler. When I do request in the form of query what should be the path? In the first case I place in the path property something like /{param} but in the second one?
You can use request.query. Four properties hold request data:
headers: the raw request headers (references request.raw.headers).
params: an object where each key is a path parameter name with matching value.
payload: the request payload based on the route payload.output and payload.parse settings.
query: an object containing the query parameters.
You can find more information in the API Reference.
Edit: Here is an example:
var Hapi = require('hapi');
var server = new Hapi.Server(3000);
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
console.log(request.query.example);
}
});
server.start(function () {
console.log('Server running at:', server.info.uri);
});
If you visit http://localhost:3000/?example=hapi, it will log hapi to the console.

Resources