Going from ASP.NET Web API to Node.js with Express - node.js

I'm challenged with the task to explore node.js as an alternative to ASP.NET Web API in providing a RESTful API.
I've been developing ASP.NET Web API for some time now and have got used to having certain things within that framework, I'm wondering what others are doing down the node.js route for some of these things: -
What ORM to use against MS SQL instead of Entity Framework
Is there a nice way of handling the routing similarly to what you get in Web API with the route template (routeTemplate: "api/{controller}/{id}")
I'm using Express so far and haven't found a way of applying something like this at a 'top level' so that I can have separate controllers...
That's it so far, I'm sure there are many, many more questions to come but those are my immediate concerns if anybody can help with these?

For ORM the 2 most libraries used are knexjs and sequelize, however, I prefer knex.
For the mapping part, as far as I know, there isn't a way to do it like in the c#. Usually what I do is, in the app.js load a file with my routes index. Here is an example,
In your app.js
app.use('/', require('./backend/routes/index'))
Then, in your routes/index
import express from 'express'
const router = express.Router()
// GET /
router.get('/', function (req, res) {
})
// GET /countries
router.get('/countries', (req, res, next) => {
})
// POST /subscribe
router.post('/subscribe', checkAuth, generalBodyValidation, (req, res, next) => {
})
// All routes to /admin are being solved in the backend/routes/admin/index file
router.use('/admin', require('./backend/routes/admin/index'))
module.exports = router
Your admin/index file can be
import express from 'express'
const router = express.Router()
// POST /admin/login
router.post('/login', (req, res, next) => {
})
module.exports = router
With this, you will be able to have a better structure for your routes.
Hope this asks your questions, if it does mark my answer as correct, if not tell me what you didn't understand :D

Related

Express JS match route without handling

Given an instance of a Express JS app or router, is it possible to match a request against the apps configured routes and receive a object that describes the route as registered with the app?
For instance, if a request for /users/1 were to be handled by the application, would it be possible for the app/router instance to programatically check if the app has a route that would satisfy this request given the URI and HTTP method?
Desirable sudo(ish) code:
const app = express();
app.use((req, res, next) => {
const handler = app.match(req);
// {
// 'method': 'GET',
// 'path': '/user/:id', <--- mainly looking for this
// 'handler': <function reference>
// }
next();
});
app.get('/user/:id', (req, res, next) => {
// fetch the user and do something with it
});
...
AFAIK there are no publicly documented Express router endpoints that provide the behavior you are describing based on its 4.x Documentation.
However, you could implement this yourself by creating a custom regular expression validator to check if the req.path string matches any defined path. The downside to this is that you would have to maintain that list separately from what is registered to Express, which might prove to be difficult to maintain.
You may be able to root through the internals of the app object to get the functionality you need, but note the instability of that approach will mean your solution could potentially be broken by non-major updates to Express.

Node dynamic routing when route is undefined

I am new with node and am trying to figure out dynamic routing. I have routes already set up such as
app.route('/users')
.get(dbController.collect)
.post(dbController.insert);
app.route('/users/:userId')
.get(dbController.read)
.put(dbController.update)
.delete(dbController.delete);
I want to be able to do something similar for routes that I have not defined in my code while still letting the routes I have defined work as usual. For example if someone was to send a get request to https://example.com/books/12 it would dynamically run the read function as it does for users.
Express routing allows you to do catch-all routes:
app.all('*', (req, res) => {
console.log('Route is unknown')
// Do something here...
})

Host React and Express on the same server?

I am working on a react site that has a contact page. On the contact page there is a text field where you enter a message that will be sent to a specific email address.
Right now I'm just trying to set up express with my react app, the only thing I need Express for is this one feature.
In my react app I am doing
$.post('http://localhost:3030/API',{value:'hi'}, function(result) {
console.log(result);
});
And in my Express index.js file I'm doing
app.get('/API', (request, response) => {
console.log(request);
})
Just as a simple test to see if things are working properly.
When I run these both and attempt to execute my post function, I get the No 'Access-Control-Allow-Origin' header is present on the requested resource. error, which is basically saying that I can't make a request to a separate domain. The issue here is not that error, but the fact that I am running my Express server and react app on two different servers.
Is there a way to have them on the same server? I am very new to back-end development, any help would be very appreciated!
Yes, React runs on the client and Express is a Node.js framework. There's a pretty good chance you're using Express if you're running any boilerplate.
Here's a pretty good walkthrough on more complete routing.
https://medium.com/#patriciolpezjuri/using-create-react-app-with-react-router-express-js-8fa658bf892d
In several of my applications my routes look something like this:
//router.js--and I'm positive this is from some react-express boilerplate
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
const react = (req, res, next)=>{
res.render('react', {
title: 'React Application',
layout: false
});
};
router.get('/app', react);
router.get('/app*', react);
module.exports = router;
//app.js
...
app.use('/', routes); //<--this is the exported router.
...
If you want to be more simple it is probably something like:
let reactRoute = (request, response, next) => {
//render your react page however you're doing that.
}
express.use('/API', yourApiFunction)
express.use('/', reactRoute)
express.use('/*', reactRoute) //Wildcards are REALLY important if you're routing inside react.
You can also bypass things with a proxy but that tends to get more complex than you probably want. Also--keep in mind you don't have to stick to Node on the back-end if you're not comfortable with it. React is client side, I use it with a few production .NET apps, some PHP (lordy!), and, yes, a lot of Node servers.
to solve No 'Access-Control-Allow-Origin' header is present on the requested resource.
you've to use the cors middleware
go to the term
yarn add cors or npm i cors
in server.js
const cors = require("cors");
const express = require("express");
const app = express();
app.use(cors());

Node.js and Express not working?

I am currently trying to learn implementing RESTful APIs using Node.js & Express. Using this tutorial: http://code.runnable.com/U7bnCsACcG8MGzEc/restful-api-with-node-js-express-4
I created each file on my local drive and tried running the code using node server.js..However I kept on getting an error. Why might be causing this?
The code you chose to run is only routing requests for urls that begin with /api as you can see here:
app.use('/api', router);
On top of that, the routes it accepts are /players and /player/:id:
router.get('/players', function(req, res, next) {
res.json({ players: players.getAllPlayer() });
});
router.get('/players/:id', function(req, res, next) {
var player = players.getPlayerById(req.params.id)
res.json(player);
});
For every request, including the routes above, it outputs the method and url to console.log.
Even when it fails to get /, you should see GET / in your console.
Now try to access this url: 0.0.0.0:8080/api/players
It works, right?

How should I implement a RESTful API with a web frontend in Node.js?

I have a setup consisting of multiple servers (written in Java) that need to communicate towards a central server, posting status updates every so often. These status updates will get written to a database, probably MongoDB/Mongoose which will be handled by the web end via REST.
I have been looking at Restify and Express as two ways to approach this problem. The website will query the database as well as the REST api.
How should I approach this? Should I use both Restify and Express to create a website with an API? Should I use Railway? Thanks.
It doesn't make sense to use a complex framework such as Railway, which is built on top of Express and tries to resemble Ruby on Rails.
You should either choose Express or Restify, not both.
I would pick Express over Restify because the code is excellently documented and the library is more mature and heavily used. You can find a bunch of useful tutorials on how to make such apps with Express, and the API is great:
var express = require('express')
, app = express.createServer();
var users = [{ name: 'tj' }];
app.all('/user/:id/:op?', function(req, res, next){
req.user = users[req.params.id];
if (req.user) {
next();
} else {
next(new Error('cannot find user ' + req.params.id));
}
});
app.get('/user/:id', function(req, res){
res.send('viewing ' + req.user.name);
});
app.get('/user/:id/edit', function(req, res){
res.send('editing ' + req.user.name);
});
app.put('/user/:id', function(req, res){
res.send('updating ' + req.user.name);
});
app.get('*', function(req, res){
res.send('what???', 404);
});
app.listen(3000);
I personally find express.js to suit my needs because of it's routing functionality that is great. Check out http://expressjs.com/guide.html#routing. It gets the job done for a RESTful api and is extremely fast.
also: Node-PerfectAPI vs Restify.js vs ExpressJS vs Node-APIServer

Resources