How to parse querystring parameter from URL in Fastify server? - node.js

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
}
})

Related

Hapjs Route Prerequisite is executed and route is always returning 404

I am building a web application using Hapijs. I am using route prerequisites to do something before the route handler is executed.
This is my route
server.route([
{
method: 'GET',
path: '/users',
pre: {
assign: 'Test',
method: async (request, h) => {
console.log('Pre route is executed.');
return "test data";
}
},
handler: userController.getUsers,
options: {
auth: 'jwt-auth'
}
},
])
But when I execute the code, it is not executing the pre route method. When the pre route handler is included, it is always returning 404 not found response. Without it, it is working. What is wrong with my code and how can I fix it?
According to the "pre documentation", "pre" should be placed inside of the "options" property and should be an array
Here is an example how what it should look like for your code:
server.route([
{
method: 'GET',
path: '/users',
handler: userController.getUsers,
options: {
auth: 'jwt-auth',
pre: [{
assign: 'Test',
method: async (request, h) => {
console.log('Pre route is executed.');
return "test data";
}
}]
}
},
])
You can get access to your "pre" data in the handler like this: const data = req.pre.Test

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

Set params on request when testing hapi routes

I am currently writing some tests for our hapi routes. The route I want to test looks like that:
server.route(
{
method: 'POST',
path: '/',
options: {
tags: ['api'],
cors: true,
handler: async (req: Hapi.Request | any, h: Hapi.ResponseObject) => {
if (!req.params.userId) {
throw Boom.badRequest();
}
return 200;
}
}});
So my test looks like this:
it('should return 200', async () => {
const request : ServerInjectOptions = {
url: '/user',
method: 'POST',
payload: {
email: 'e#email.de',
password: 'secred',
firstname: 'John',
lastname: 'Doe'
},
app: {}
};
const response = await server.inject(request);
expect(response.statusCode).toEqual(200);
});
As you can see the route expects a param in the params array with the name userId but i am not able to set the parameter on the ServerInjectOptions object. The error I get is that the property does not exist on the ServerInjectOptions type.
Is there any other way i can set the params array? I didn`t find something in the docs maybe i missed it and someone can tell me where to find it.
Thanks in advance
For the route I believe you add the name of the parameter to the path like so:
server.route(
{
method: 'POST',
path: '/:userId',
//
}});
And for the test you should be able to add your parameter to the url option:
const request : ServerInjectOptions = {
url: '/user/parameterYouNeedToAdd',
//
};
Or if the parameter is a variable:
const request : ServerInjectOptions = {
url: '/user/' + parameterYouNeedToAdd,
//
};

Nodejs - HTTP - with optional parameter

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.

Request parameters while consuming a REST API in node.js

I would like to consume a REST service in Node.js using request.js, as follows:
var request = require('request');
request.get({
url: 'https://www.googleapis.com/storage/v1/b',
auth: {
'bearer': 'oauth2_token'
}
}, function(err, res) {
console.log(res.body);
});
However, I would like to specify also a set of request parameters, such as project, prefix, etc. (as specified at https://cloud.google.com/storage/docs/json_api/v1/buckets/list).
How can I pass these parameters in the request for consuming the API service?
You can pass in qs as the additional queries. See example below:
const queryObject = { project: 'project', prefix: 'prefix' };
request.get({
url: 'https://www.googleapis.com/storage/v1/b',
qs: queryObject,
auth: {
'bearer': "oauth2_token"
}
}, function(err, res) {
console.log(res.body);
});
See here for github issue.

Resources