$resource.query() parameters fail to arrive at server - node.js

Trying to implement a RESTful API using Node.js and Angular.
On the client side, I define a resource called songResource with the $resource function in Angular.
I then call the API with this method:
$scope.displayArray = songResource.query(
parameters, // an object containing various settings
function(value, responseHeaders) { // success callback
console.log('Success!',parameters);
...
},
function(httpResponse) { // error callback
console.log('Error!');
...
}
);
On the server side, the route resolves, but the parameters do not come over. (In other words, req.params is an
empty object.) The rest of the service retrieves and sends zero records. My client receives the zero records and
hits the success callback, where I can tell that the API call succeeded.
Why aren't the parameters coming over to the API, and how do I fix this?

Found out what I was doing wrong. My parameters come in through the query string. Therefore, I need to use req.query rather than req.params to get the parameters.

Related

use req.body data from the api route handler in a external javascript file in nextjs api

I need to send the req.body (data received from the client to API route via post request) data from the API route to a separate javascript file in the backend api.
const payload = {}
const handler = async (req, res) => {
payload = req.body
res.status(200).json({ status: 'success' })
}
export default handler
I declared a variable outside the route handler function and assigned req.body to it, but then I realized that I can't use this global variable inside the handler function. I don't know the reason. Is there any specific way of achieving what I'm trying to achieve here?
I request to please elaborate the use case a bit more. Based on current requirements.
I can understand that-
You need to send the req.body to another JavaScript file. Now here can be 2 cases.
You need to store req.body in a file, and use it for later processing.
Pass the req.body to another function which is present in another JavaScript file.
In this case, you can export the function from another file and import in this main file and call the function in your controller and pass req.body as Payload.
I think your use case will be second one, if not please update question and I will be happy to help you out.

Express Sessions GET vs POST requests

I can access the session object data when using post method but session object data is null when using get method.How can i access session object data using get method.
I am using express-session.
Front-end Code
For POST method
axios.post(url,{params:data},{withCredentials: "true"})
For GET method
axios.get(url,{params:data},{withCredentials: "true"})
Back-end Code
Middleware for both get and post requests.
router.use((req: Request, res: Response, next: NextFunction) => {
console.log(req);
if (req.session && req.session.username) next();
else res.status(401).send("Unauthorized");
});
axios.get() only takes two arguments (not three). The first is the URL and the second is the options. You are passing the options in the third spot which axios.get() does not look at. Therefore, it never sees the withCredentials: true option and thus doesn't send the session cookie and thus your server doesn't know how to find the session.
So, change from this:
axios.get(url,{params:data},{withCredentials: "true"})
to this:
axios.get(url,{withCredentials: "true"})
Note, there is no data argument for axios.get() because a GET does not send a request body, only a POST or PUT send the body. See the doc here.
Note: This bites people regularly with axios. .post() and .get() need a different number of arguments.

At what point are request and response objects populated in express app

I’m always coding backend api’s and I don’t really get how express does its bidding with my code. I know what the request and response objects offer, I just don’t understand how they come to be.
This simplified code for instance:
exports.getBlurts = function() {
return function(req, res) {
// build query…
qry.exec(function(err, results) {
res.json(results);
}
});
}
}
Then I’d call in one of my routes:
app.get('/getblurts/, middleware.requireUser, routes.api.blurtapi.getBlurts());
I get that the function is called upon the route request. It’s very abstract to me though and I don’t understand the when, where, or how as it pertains to the req\res params being injected.
For instance. I use a CMS that modifies the request object by adding a user property, which is then available globally on all requests made whether ajax or otherwise, making it easy at all times to determine if a user is logged in.
Are the req and res objects just pre-cooked by express but allow freedom for them to be modified to your needs? When are they actually 'built'
At its heart express is actually using node's default http-module and passing the express-application as a callback to the http.createServer-function. The request and response objects are populated at that point, i.e. from node itself for every incoming connection. See the nodeJS documentation for more details regarding node's http-module and what req/res are.
You might want to check out express' source code which shows how the express application is passed as a callback to http.createServer.
https://github.com/expressjs/express/blob/master/lib/request.js and https://github.com/expressjs/express/blob/master/lib/response.js show how node's request/response are extended by express specific functions.

POST Method in Feathers Example

Can someone explain, how I make a POST method using Feathers and test it in postman. I notice that there are two parameters, "data" and "params". What are their differences? Can someone give me a complete example how to create POST method in feathers and test it in postman?
Thanks
The data is the actual data passed to the service method, ex: a form data. and the params contains the provider (i.e REST, Socket.io or Primus), connection details, authenticated user details and other info related to that service.
For post method you can use the create(data, params) method of the service that you are calling and do your post activity there like creating records like below.
app.use('/messages', {
messages: [],
create(data, params) {
this.messages.push(data);
// Your post activity here
return Promise.resolve(data);
}
});
And in postman use can use the URL http://localhost:3030/messages and in the request body provide the JSON you want to pass as a data to the POST method
ref: https://docs.feathersjs.com/api/services.html

mean.js $resource to call express server RESTful API

I come from a completely non web-development background, but having seen the traction that mean.js is picking up, i really wanted to give it a shot.
I've followed tutorials online so I've basically started, run and modified the example app but am now trying to do something thats off of the tutorials. As a result I have a basic understanding of express and angular
I've been trying to integrate the activator npm package (https://www.npmjs.org/package/activator) into the app, and while I've managed to fit in the angular bits, I'm having trouble plugging in the express bits. Which brings me to a very fundamental doubt, the answers to which I haven't really been able to find. I know that in Mean, the angular code connects to the express code using REST API's created in express. And that I believe happens using angular services. But I don't understand how. For instance, the users module has the following service defined:
angular.module('users').factory('Users', ['$resource',
function($resource) {
return $resource('users', {}, {
update: {
method: 'PUT'
}
});
}
]);
Can anyone explain how this works ?
Also if I have some code on the express side say:
var sayHello = function(name){
return "Hello"+name;
}
How can I call this through angular? I know we use $resource for that from the ngResource module, but I dont really understand how.
Any help would be much appreciated.
Connecting these things together can be a bit confusing. I think the thing to understand is that when using Express on the server side, you need to model your API around a route, and handle communication with the req and res objects you'll be handed.
So first on the client side, taking a simple example, I generally use the $resource as a way of wrapping the HTTP/ajax details which I don't want to worry about. So I'll write my service as such:
"use strict";
angular.module("myModule").factory("UserService", ["$resource",
function($resource) {
var resource;
resource = $resource("/api/users", null, {
listUsers: {
method: "GET",
isArray: true
}
});
return resource;
}
]);
(Notice that I'm passing the isArray parameter to this resource since I expect an array of users to return -- which is not always the case with all APIs).
Then to take advantage of that resource, perhaps in my controller I'll have code like this:
"use strict";
angular.module("myModule").controller("UserCtrl", ["$scope", "UserService",
function($scope, userService) {
$scope.loadUsers = function() {
userService.listUsers(function(resource, headers) {
// this function is called on success, with the result
// stored within the `resource` variable
// ...
}, function(response) {
// this function is called on error
// ...
});
};
}
]);
Now assuming everything goes right on the server side, we'll receive our list of users to play around with passed in to the first function as the resource.
On the server side, we'll need to configure our routes (wherever those are configured) to include our users controller, which will serve as our users API. So perhaps within this app we have a routes directory which contains all our Express routes (see the app.route documentation for more information on Express routes). We also have a controllers directory which contains all our Express controllers that handle the logic for our routes. Keeping with the "users" example, we'll have a route defined that matches the /api/users $resource route we defined above in our Angular code:
"use strict";
var controller = require("../controllers/user");
module.exports = function(app) {
app.route("/api/users").get(controller.listUsers);
};
This code takes in the Express app as input, and defines a single route for /api/users as a GET HTTP request (notice the .get function called). The logic for this route is defined in the user controller, which would be something like this:
"use strict";
exports.listUsers = function(req, res) {
var users;
// ...somehow populate the users to return...
res.send(users);
};
We've left the details on how to populate that array of users, but hopefully this gives you the idea. This controller is passed the req (request) and res (response) HTTP objects as input, so it can query the request object for details on what the user passed in, and must send some response back to the user to complete the request/response loop. In this example I'm using the res.send function to simply send back our JavaScript array (which will be passed as JSON).
Does that make sense?

Resources