Bolboa Bolboa - 2 months ago 24
Node.js Question

Use node js as backend for ionic framework

I followed the following tutorial to create a RESTApi for my node server...https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

My server file now has routes that allow it to to make GET and POST requests which I've tested on Postman and they work. My server file is pretty long but here is an excerpt to get an idea of how it works...

router.route('/bears')
// create a bear (accessed at POST http://localhost:8080/api/bears)
.post(function(req, res) {

var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)

// save the bear and check for errors
bear.save(function(err) {
if (err)
res.send(err);

res.json({ message: 'Bear created!' });
});

})
.get(function(req, res) {
Bear.find(function(err, bears) {
if (err)
res.send(err);

res.json(bears);
});
});
router.route('/bears/:bear_id')

// get the bear with that id (accessed at GET http://localhost:8080/api/bears/:bear_id)
.get(function(req, res) {
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
res.json(bear);
});
});
...etc,etc


Now, since I am using an ionic framework I need to configure it to use this server as a backend.

My problem is, how do I connect to it using angular?

All my routes are prefixed using
/api


app.use('/api', router);


So I tried the following...

app.factory('Bear', function ($resource) {
return $resource('http://XXX.XXX.X.XX:3000/api/bears/:bearId');
});


But I'm not sure this is working. I want to make one Post request so that I can test that the backend is working but I do not know what code to add to do so.

For example, if I have a form on my
index.html
and I send this info to my angular controller, how can my controller take this info and make a post request to my server? I've been trying to figure this out for days.

Answer

If you just want to test that your backend is working, check out postman.

Here's how you can refactor your code. First, note that as it is currently, how you're using $resource isn't actually make any calls to the API. You should inject your Bear service in a controller or another service somewhere in your app, depending on how you're going to use the bears. Then, in this other service or controller, you would do

var result = Bear.get({ bearId: <value> }) or var result = Bear.post({ bearId: <value> })

or whatever other http method you want to use. The resource object will then automatically hit the URL endpoint with the specified HTTP action and the parameter you have provided and then return you back the result.

Check out the $resource documentation for more detail. Also, the fact that you're using ionic has no bearing on connecting to the API.