I am using node.js express to build simple rest API, I had built a API like
app.get('/sites/:site/:building/:floor',function(req,res){
var building = req.params.building, floor = req.params.floor, site = req.params.site;
console.log('query site ',site,building, floor);
.....
}
when client did the AJAX request in angular.js
$http.get('/sites/london')
.success(function(data) {
}).error(function(data, status, headers, config) {
});
the server doesn't respond to this kind of URL, unless I changed the express API to
app.get('sites/:site',function(){})
app.get('sites/:site/:building',function(){})
app.get('sites/:site/:building/:floor',function(){})
But the way above is too tedious so I wonder if it is possible to build API in one sentence app.get('sites/:site/:building/:floor',function(){})
The following stackoverflow answer should help you out. But to answer your question, the below should work
app.get('sites/:site?/:building?/:floor?',function(){})
Related
Hi I have a node based server api, and have created a simple web app using angular 2.But I don't understand how to integrate both. I have done a little research but most of the websites are only offering how to built angular 2 application and no one offers node integration.
Notice that Nodejs is simple server-side Javascript, so you have to follow one of these approches:
Server side web app:
In this case all pages (and functionality) will render in server-side. You can find lots of framework for doing that. So you need no client-side framework like angularjs.
Client side web app + server side api: I think that is something you need. Server side api has build as rest api service and serves all your business functionality. In client-side angular just consumes these services. All client based functionally will handle with angularjs (like routing, async service call, manages states and etc)
Or if your question is how comminucate with node-js rest api look at this page: angular2 http
You can install any web server for angular like apache or nginx. For example u're using apache, when you run apache you can access angular web through http://localhost/project.
Follow this tutorial on how to install and run nodejs http://blog.modulus.io/absolute-beginners-guide-to-nodejs on window. On mac https://shapeshed.com/setting-up-nodejs-and-npm-on-mac-osx/
You can call node server using REST API.
In your angular service for example :
$http.get('http://project/rest/getData', succFn).then(function (res) {
return succFn(res.data);
}, 'error');
In nodejs (REST Server) :
apiRoutes.get('/getData', function (req, res) {
// Return any data to client
res.json({
'code': '00',
'content': 'Return dummy or json here',
'remarks': 'Success'
});
}
I'm trying to use the res.send() from Express into a Meteor project without using a Meteor package like glittershark:meteor-express: https://github.com/glittershark/meteor-express
I'm wondering if there is a solution just using Meteor rather than adding Express on top of Meteor? In particular, how do I use res.send() in Meteor?
http://expressjs.com/4x/api.html#res.send
This is the NodeJS code snippet from https://github.com/twitterdev/cannonball-web/blob/master/routes/index.js
var express = require('express');
var router = express.Router();
var request = require('request');
request.get(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Send the verified phone number and Digits user ID.
var digits = JSON.parse(body)
return res.send({
phoneNumber: digits.phone_number,
userID: digits.id_str,
error: ''
});
}
One great answer posted a year ago suggests using fibers. Meteor has undergone a lot of changes since this post and I'd like to avoid fibers:
Is there an easy way to convert an express app to meteor?
I'm adding this link to another relevant answer posted that might be helpful in anwering my question: Porting Express App to Meteor
Thanks for reading. :)
There are many good, simple ways you can add a rest api that serves json to a meteor app (I recommend restivus), however the requirements you are forcing on yourself are only going to make it difficult for you.
WebApp.connectHandlers and connect is the low level apis that you can use, but you are only asking for further difficulties by wanting to avoid Fibers, as this simply is how things are done in Meteor.
Rather then trying to force square pegs into round holes, I suggest you do one of the two following options:
Use one of the recommended options for adding a rest api to a Meteor app
Have a expressJS app running beside your Meteor app to serve the api, and simiply accessing the same MongoDB.
How to Handle a Coinbase Callback in NodeJS to Recieve Instant Bit Coin Payment Notifications ?
Please I need example.
Note : I'm using SailsJS MVC Framework.
OK, based on your comment, I will give it a go.
I am assuming you have (or will have) an ExpressJs app.
UPDATE Sorry, I just noticed you're using sailsjs. The below should still be valid but you'll need to adapt it to work with the sails routing engine.
In your app, you need to define the post route:
// the app variable is the express js server
// name the route better than this...
app.post('/coinbase', function(req, res){
var data = req.body;
var orderId = data.order.id;
// etc...
});
What is the best way to send POST request from node server which has received the request parameter from a client? Reason I am asking for best practice because it should not affect the response time if multiple clients are calling the node service.
Here is the Backbone Model which sends the request to node server:
var LoginModel = Backbone.Model.extend({
url:'http://localhost:3000/login',
defaults: {
email:"",
password:""
},
parse: function(resp) {
return resp;
},
login: function() {
console.log('Here in the model'+JSON.stringify(this));
this.save();
}
});
var loginModel = new LoginModel();
Node Server
var http = require('http'),
express = require('express');
var app = express();
app.listen(3000);
app.post('/login', [express.urlencoded(), express.json()], function(req, res) {
console.log('You are here'); console.log(JSON.stringify(req.body));
//Send the post request to third party service.
});
Should I use something like requestify inside app.post() function and make a call to third party service?
I like superagent personally but request is very popular. hyperquest is also worth consideration as it resolves some issues with just using the node core http module for this.
Reason I am asking for best practice because it should not affect the response time if multiple clients are calling the node service.
First, just get it working. After it's working you can consider putting a cache somewhere in your stack either between your clients and your api or between your server and the third party api. I'm of the opinion that if you don't know exactly where you need a cache, exactly why, and exactly how it will benefit your application, you don't need a cache, or at the very least, you aren't prepared instrumentation-wise to understand whether your cache is helping or not.
I have a RESTful Java backend which I made using Jersey, a JAX-RS implementation. This backend is running on a glassfish server on port 8084. I've also made some HTML5/JS/AJAX pages which display the data so I know my REST implementation is working.
I'm trying to develop an HTML5 / JS frontend for this application using the Angular.js framework but I'm experiencing some trouble. I have managed to develop some small webapps in angular which I'm running on Microsoft's IIS on port 80.
Unfortunately, there appears to be a problem with the communication between the two applications. Since I'm new to Angular, I'm unsure if I made a mistake in my frontend code, or if I'm experiencing CORS problems. I already tried running the backend on a Tomcat 7 with the CORS filter but that didn't solve anything.
My angular code looks like this:
services.js
var serviceModule = angular.module('ServiceModule', ['ngResource']);
serviceModule.factory('NodeService', function($resource) {
var NodeService = $resource('http://localhost:port/HtmlJerseyJava/service/node/get/3',{},
{
'get' : { method: 'GET',params:{port:':8084'}}
}
)
return NodeService;
});
controllers.js
function NodeDetailCtrl($scope, NodeService){
var node3 = NodeService.get();
$scope.data = JSON.stringify(node3) ;
}
I hardcoded the ID 3 for now, because I also need to figure out how I can pass the value of an input field from the view to the controller and then to the service. Eventually, the 3 in the service url would be replaced by a variable :nodeId
Any help would be greatly appreciated.
Try the following simplified code:
app.js (for test purposes I suggest you to put functions in one js file)
var serviceModule = angular.module('ServiceModule', ['ngResource']);
serviceModule.factory('Node', function($resource) {
return $resource('http://localhost:port/HtmlJerseyJava/service/node/get/3',{port:':8084'},
{
get {method:'GET'}
});
});
serviceModule.controller('NodeDetailCtrl', function($scope, Node){
$scope.data = Node.get();
}
It would be interesting to now what JSON data your client gets from the REST call.
Greets Marc
I found the solution. There were several steps to fix this problem:
Add a CORS filter to the Jersey servlet on Glassfish.
Upgrade the Angular version to 1.1.x (currently still unstable)
Set a custom header in your resource.
Enjoy a working application.
Big thanks Marcbaur for helping me out here.