I have a question about express.js. Recently, I'm writing a small project. but how to route to "http://localhost:3000/upload/t/t" like this. I can only navigate to localhost:3000/upload
Just make Get Request as per below.
var app = express();
app.get(['/upload/t/t'], function (req, res) {
//Write your code.
})
Related
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
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());
Hello guys i'm new to node js and started researching and working on some tutorials. I just want a better understanding or clarification on a doubt i had. So i came across the in built module http. This helps in creating a a basic web server. Now express module is a web framework that is built on top the http module that makes it easy using a fully wedged web server without reinventing the wheel. Now I came across this code:
var express = require( 'express' )
, http = require("http")
http.createServer( options, function(req,res)
{
app.handle( req, res );
} ).listen(8080);
But in express one could simply just do this
var express = require('express');
var app = express();
app.listen(8080, function() {
console.log('Listening on ' + 8080);});
What's the difference between both? Don't they both accomplish the same thing. If not what's the difference and advantage of using the first approach. Should one adhere to the first approach as it's a good programming practice. That's my doubt as i just want a clear understanding if there's any difference.
Why combine http module with express module
There's really no reason to create your own http server using the http module. Express will just do that for you with app.listen() just fine and save you little bit of typing.
If you were creating an https server, then you would need to use the https module and pass security credentials to https.createServer(...) in order to create a properly configured server. Express does not have the ability to create a properly configured https server for you automatically.
If you look at the Express code in GitHub for app.listen(), it shows this:
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, there's really no difference (other than a little less typing) when you use app.listen() or create your own http server and then use app as the listener to that server.
So, these two code snippets are identical in function:
var app = require('express')();
app.listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
The above code is functionally identical to:
var http = require('http');
var app = require('express')();
http.createServer(app).listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
Of course, if you're trying to set up https servers or add custom options to the .createServer() method, then you will set up your own server first and then pass app to it as the listener. app.listen(...) is just a shortcut when the default http.createServer() works fine.
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?
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