How to Send Ajax Parameters through angular server route? - javascript

I am using MeanJs Stack
I need to call the following Api :
http://localhost/api/movies/movieId/Action?page=1&perPage=10
How to send params (page='+:id+page='+pageNum+'&perPage='+perPage) in Server Route
I am sending the Following way which is not Helping
movies.server.routes.js
app.route('/api/movies/:id/Action?page='+:id+'page'=+pageNum+'&perPage'=+perPage')//But it is not recognising by rout and parameters are not sending
.get(movies.readAllMovies);//triggers and call the api .
Could you guys give me some Hint of it ?
Sorry for the horizontal scroll guys :-) .
Thanks.

According to ExpressJS documentation, query strings are not part of a route definition.
Therefore, your route could be refined (apart from having a couple of syntax errors) as such:
app.route('/api/movies/:id/Action')
.get(movies.readAllMovies);
Then, in the handler movies.readAllMovies, you can access query strings with req.query. That is, the page query string can be retried as req.query.page and so on.
Note that since expressJS uses regular expressions to match routes, a ? will serve as a quantifier in regular expression terms.

First of all, in my opinion, you should be handling this through a service to return the result, and a RESTful endpoint on the node server to perform the query. I feel your above approach could use a serious re-visit conceptually, so here's how I'd tackle it.
You need to create a service or a factory for handling the requests to the api endpoint
Check out the below instructions for modifying your api endpoint so that it just pipes the response back to the service
Include the service in your angular module and consume it on demand in your controller / whatever
You should use request module and params, it is by far the easiest method of retrieving query params in get requests in my opinion and streaming the response is to just pipe the result of the url. This is super simple using request https://www.npmjs.com/package/request
First, lets modify your endpoint and include the request module
First npm install request --save
Then in your app include request var request = require('request');
req.query.--name of queryparam
and
req.params.--name of param
Then your endpoint is as simple as
app.get('/api/movies/:movieID/:Category', function(req, res){
var url='http://localhost/api/movies/' + req.params.movieID + '/' + req.params.Category +'?page=' + req.query.page + '&perPage=' + + req.query.page;
request(url).pipe(res);
});
**You should be able to hit this endpoint directly with a get request and it should work
Then Create a Service to consume the result and provide it to the controller

Related

why can't I pull HTTP requests after configured controller in nest.js

So, the person who left the company used Nest.js write this server side.
He has auth.controller, auth.service,auth.module,auth-token,jwt.strategy and jwt-payload all set up well, and I checked his module, everything is imported and the providers are being set up well.
But in front-end I do send HTTP request in any end point, I just always get code 404.
even if i wrote a simple end point like this :
*#Get('/meow')
toMeow(){
return 'meow';
}*
in his controller file, I still can't pull any HTTP request.
In his other folders controller ,I do can pull the HTTP request well with same address plus the routes
What's the reason for this?
My coworker solved it, I didnt register jwt.strategy to the Module

Why does an Express function take both the Request and Response as arguments?

I am new to node.js and am acquainting myself with Express. The following code is my source of confusion:
var server = http.createServer(handleRequest);
function handleRequest(req, res) {
var path = req.url;
switch (path) {
case "/n":
return renderPage_1(req, res);
default:
return renderPage_2(req, res);
}
}
I understand that the server needs to accept an HTTP request(req). However, if we are returning a response, why is the response also an argument in the callback function? I keep running into a dead-end thinking that it has to do with the scope of the response object, though I am not sure.
I would greatly appreciate clarification on this matter. I have not been able to find a resource that delineates my confusion.
Best,
Abid
I think the answer to your question is that this is how the authors of express decided to implement the library. At a high level, express is really just a light-ish weight wrapper that makes it easy to build middleware based http services with NodeJS. The reason that both the req & res objects are passed to each express middleware function is that in practice, web services are rarely able to fulfill an entire request in a single step. Often services are built as layer of middleware the build up a response in multiple steps.
For example, you might have a middleware function that looks for identity information in the request and fetches any relevant identity metadata while setting some auth specific headers on the response. The request might then flow to an authorization middleware that uses the fetched metadata to determine if the current user is authorized and if the user is not authorized can end the request early by closing the response stream. If the user is authorized then the request will continue to the next piece of middleware etc. To make this work, each middleware function (step of the stack) needs to be able to access information from the request as well as write information to the response. Express handles this by passing the request and response objects as arguments to the middleware function but this is just one way to do it.
Now the authors could have decided to implement the library differently such that each route handler was supposed to return an object such as { status: 200, content: "Hello, world" } instead of calling methods on the response object but this would be a matter of convention and you could pretty easily write a wrapper around express that let you write your services like this if you wanted.
Hope this helps.

Node.js get value from end of url

Is there a way for me to create a URL like this: http://localhost/example/143 and use 143 as an id to fetch content? I do not want question marks or other things like this. An example website like this is imgur which doesn't use question marks.
I have looked for other options, but all of their questions requires ?=somequery in order for it to work.
Thanks
Use express.js named route parameters: http://expressjs.com/en/guide/routing.html#route-parameters
Use req.params as in express documentation
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
In case of using raw http
for using with raw http module you can use str.split("/")[2];
var http = require('http');
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
var str = request.url;
var exampleId = str.split("/")[2];
}
var server = http.createServer(handleRequest);
server.listen(8080, function(){});
What you are describing is what's referred to as a restful web api implemented with routing You'll typically want to build your site in a MVC (Model View Controller) framework to get this functionality. Express.js is new hotness on the block - especially in the context of javascript and node.js categories tied to this question - but there are others out there as well. Ruby on Rails made MVC and restful routing popular, and MS has ASP.NET MVC. PHP even has CodeIgniter and others I'm sure, and Angular2 is Google's MVC baby at the moment.
The point is, there are many frameworks to choose from that will give you the restful URL routing you're looking for. Find one you like, and run with it!

REST API endpoint test (request / response code)

I m actually building a REST API that I need to test.
Actually, I have many unit tests to check each method behaviour and now I need to test if I get the expected result when requesting an endpoint, like checking the HTTP response code.
I m working with nodejs and it seems to be a good idea to use supertest module to send HTTP request and to check response codes.
The fact is that if I send request on my real REST API endpoints, I can have many bad data managed in database (when testing PUT / POST / PATCH methods).
But in the other hand, I don't have (in my mind) any way to "mock" or simulate my business job inside of the tests :
(Mocha syntax with ES6)
describe('get /v1/clients ', function() {
it('Should get 200 ', function(done) {
request.get('/v1/clients')
.query('access_token=' + token + '').expect(200, done);
});
});
So you've probably got it :
I want to test each API endpoint to be sure that I get what I should get
I want to use a standard access_token, not one my database (like a fake one)
I want to "simulate" by API, without using real data.
Is that possible ? If yes, How ?
Is this a better choice to check on my real data or not ?

Angular JS - Express Routing

I am running a MEAN framework with express routing requests. I have two main routes to public/ and app.
With the APP being an API and public being a set of web pages which reads data from the API.
// Setting the app router and static folder
app.use(express.static(path.resolve('./public')));
I have two controllers in the public folder, home and header.
In the home controller I am using Angular JS to call the API and return the results.
The API allows for filtering through the use of query strings:
$http.get('http://search?sumBoth=1&customer=' + customer)
I would like to build up a route specific to this controller along the lines of
http://url/customers/CustomerName
Where CustomerName would be set as the customer variable
Question
a) Is this best done in Angular or Express?
b) Where and how do I implement such routing?
I hope this question is well received, please comment, if you need more information.
I understand that the response of $http.get('http://host/path?sumBoth=1&customer=' + customer) is a list of search results. In that case the path should be a collection path, it's not really a best practice to have search terms in the path. Subcollection paths are pretty standard (something like http://host/customers/search?params, but still the specific search terms should go in the query string)
If on the contrary you expect to retrieve just one result by some identificator (provided for instance the customer name is unique) that's a different story, you should really use http://host/customers/:identifier.
In any case you can use angular resources, both parts of your application need to be aware of the routing. In the front-end you define an additional verb that adds the filters (or just use the standard query one - see https://docs.angularjs.org/api/ngResource/service/$resource). In the back-end you need to route the call and parse the parameters. If it's a list, parse the query string and render your result array, if it's a single resource, parse the identifier, find the corresponding resource and render it back.

Categories