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!
Related
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
I'm connecting to an external API on my backend.
Data flow : External API -> My backend -> Client side
I know that exists modules like request or http that helps this process.
But, When I receive the data from External API, I need to modify it and add some information. After I'll send this "modified data" to the Client side.
I am searching a tool similar to BackBone Collections on the backend to help me. BB Collections have awesome functions like fetch/sort/each.
Every time I google only I found frameworks like BackBone on the client side not on the server side.
Edit 1
Tool would have to help me iterating over array (received from external API) or accessing to item with specific attr given.
Solved
After studying both options (Lodash and Unirest), finally I decided to use Lodash combined with request.
Try lodash to handle arrays in server side.
var unirest = require('unirest');
app.get('/api', function(req, res){
unirest.get('http://localhost:3000/getlist')
.header('Accept', 'application/json')
.end(function (response) {
response.body.forEach(function(item){
//handle item
});
res.send();
});
});
Maybe Unirest?
I am new to express js so please bear with me.
I am reading "MEAN Web Development" by Amos Q. Haviv and it is a very good book however, there is a part that baffles me.
In order to send backend vars/data to the client you have to store them in the window object and then use angular js to intercept that data with a service. Something like this:
angular.module('users').factory('Authentication', [function() {
this.user = window.user; //DATA FROM DB
return {
user: this.user; //DATA NOW ACCESSIBLE TO THE CLIENT
}
}]);
Is that right? If that is the only way to do it THAT SUCKS! Seems very cumbersome to me.
Does anybody out there have a better way of doing this?
It sure sucks.
Implement RESTful architecture and request data from Node.js via an API using Angular $http or $resource.
For regular server to client and bi-directional communication Angular is the wrong answer, since it's based on HTTP. In this case you need to use WebSocket.
I'm an html5 developer with mainly JavaScript experience. I'm starting to learn the backend using Node.js. I don't have a particular example of this question/requirements. I'd like to call a back end function with JavaScript, but I'm not sure how. I already researched events and such for Node.js, but I'm still not sure how to use them.
Communicating with node.js is like communicating with any other server side technology.. you would need to set up some form of api. What kind you need would depend on your use case. This would be a different topic but a hint would be if you need persistent connections go with web sockets and if you just need occasional connections go with rest. Here is an example of calling a node function using a rest api and express.
var express = require('express');
var app = express();
app.post('/api/foo', foo);
function foo(req, res){
res.send('hello world');
};
app.listen(3000);
From the frontend you can post to this REST endpoint like so.
$.post("/api/foo", function(data) {
console.log( "Foo function result:", data );
});
If you're just starting with node-js, don't worry about Websockets just yet.
You're going to want to create a REST API (most likely) depending on what you're trying to accomplish. You can put that REST API behind some kind of authentication if desired.
A REST API is going to have endpoints for creating/deleting/updating and getting (finding) a document, like a given user.
My recommendation is to work backwards from something that's already working. Clone this app locally and check out the controllers to see examples of how this application interacts with creating users.
https://github.com/sahat/hackathon-starter
Once you create a controller that returns data when a client hits an endpoint (like http://localhost:3000/user/create ) , you'll want to create some HTML that will interact with endpoint through a form HTML element. Or you can interact with that endpoint with Javascript using a library like jQuery.
Let me know if that makes sense to you. Definitely a good starting point is to clone that app and work backwards from there.
Can I suggest trying api-mount. It basically allows calling API as simple functions without having to think about AJAX requests, fetch, express, etc. Basically in server you do:
const ApiMount = apiMountFactory()
ApiMount.exposeApi(api)
"api" is basically an object of methods/functions that you are willing to call from your web application.
On the web application you then do this:
const api = mountApi({baseUrl: 'http://your-server.com:3000'})
Having done that you can call your API simply like this:
const result = await api.yourApiMethod()
Try it out. Hope it helps.
i'm currently trying to display the name of the logged-in user in my MEAN app. I'm using the EJS templating engine and I'm able to get the username showing by putting <%- user.username %> in my markup. The problem with this is that I don't really want to my mixing angular and embedded scripts in the same files, I'd like to pass the server-side data into Angular. I've tried ng-init but I'm not having any success at all with it.
I will assume you are using ExpressJS 4 it will be a little different in version 3, however the approach will be the same for both versions:
Node/Sever side
var express = require('express');
var bodyParser = require('body-parser');
var schema = require("./schemas");
var app = express();
var router = express.Router();
router.get('api/account', function(req, res){
res.json({ "login": req.session.user.login }); /*access the session account not sure if this matches your login location you will adapt it to your own*/
});
Angular/Client Side
You then invoke from your controller or service the url api/account with a GET request to receive the JSON like:
$http.get("/api/account").then(function(data){ console.log(data); });
then you could do something like:
$scope.login = data.login;
and in the html
{{login}}
From what I understand of Angular, it discourages server-side setting of templated values in HTML code. Consider setting up a JSON service that provides the data, and fetching the data over JSON. There is an example at the end of the Angular Tutorial that may make this clearer.
I do the exact same thing and mix EJS to embed things like my server info (to initiate a socket connection from the client). If you wanted to keep this purely client-side, you would need to have AngularJS fetch the server-side data using a service / factory - and then affect any views you have depending on said data.
ng-init only applies to things which live inside the "Angular" scope.