I built a simple web portfolio page with html, css and javascript. I did it with no framework like angular or react. I used bootstrap for my footer alone.
I used webpack as my bundler and everything is working just perfect but my problem right now is that I want to integrate express.js with my app and I have no idea how to do that, I'm about finishing Server side programming with Nodejs and Express course from Coursera. I have searched through google but couldn't find what I want.
There are different ways to integrate your backend with your frontend. You said you were finishing up a course on Node JS and Express on Coursera so I'll assume you already know how to set up your server and whatnot.
If you're starting out and just want to have your data coming from a database and have it populated in the actual HTML I would take a look at EJS. It allows you to embed data into an HTML page, that way you can generate a finished HTML page with all the data you need. This is great for things like SEO.
Another way is to have some client-side Javascript that queries your backend via a REST API in some way like:
In Express:
async function getSomethingFromDB(req, res) {
const data = await getDataFromDb()
res.send(data)
}
app.get("/something", getSomethingFromDB)
In your frontend JS:
async function fetchDataFromBackend() {
const res = await fetch(`/something`)
const data = await res.json()
return data
}
You can call fetchDataFromBackend however you want and do whatever you need with data, such as populating your website with this data. This approach is great to make interactive applications but has its own problems regarding SEO and I would advise the first method, using this technique once you require AJAX in your website.
I hope this helps!
Install in your backend project folder, in console: npm install express --save
var express = require('express');
var app = express();
// Configure headers y cors
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
next();
});
app.use('/api', project_routes);
If you want to expose your back-end API to your front-end in a simple way, can I suggest using api-mount which is based on express under the hood.
Should you need to customize express, introduce additional middlewares or similar - api-mount allows that.
The downside is that your back-end would not be RESTfull and you would learn less about express itself. Still, try it out - you might like it :)
Related
I'm working on a small ToDo app where I've Angular as front-end and Node.js/Express/Mongo as middleware/backend.
While I submit Login in my Login form, it hits the login API, however it returns one strange output in the console saying
OPTIONS http://localhost:3000/api/v1/users/login/ 0 {}
(see screenshot below) which doesn't allow me to get the dashboard even after successful login.
I've enabled CORS through installing the cors NPM module. and I've checked RESTFul services in Postman, and all are working fine.
[Updated] This is how I've enabled the CORS in my express.js's app.js file.
let cors = require('cors');
app.use(cors());
app.options('*', cors());
before a CORS request is sent to the server, clients will always send this "OPTIONS" request as a "preflight request", soliciting supported methods from the server.
This request being blocked may be an indicator of a wrong CORS configuration or an explicit block of all "OPTIONS" requests from the server. (CORS needs to be configured on the server as well).
More information can be found here
It seems that this is a known nodejs issue that is still open.
Based on the open github, seems that the best recommendation is to try something like this:
you need to allow both:
// Http.OPTIONS method for request that is hitting " apiUrl =https://127.0.0.1:3000/login".
// Allow CORS like below:
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'content-type');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
Another great idea is to use the angular proxy settings for local development so that you will not need to add CORS for localhost at all.
Very good guidance in this SO answer here on setting up a proxy for angular If this work, then you can make 100% sure that it is indeed a CORS problem.
To handle CORS in express you dont need to add any dependency.
Notice that http://localhost:4200 is you angular app.
This worked for me:
//Add here whatever route you are using for the api.
app.use('/api', (req, res, next) => {
//Where http://localhost:4200 is the angular app
res.header('Access-Control-Allow-Origin', 'http://localhost:4200'),
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
next();
})
Note:
This goes after the place where you import the routes and before where you use them. kind of like:
const apiRouter = require('./app_api/routes/api_routes');
//The code i posted here
app.use('/api', apiRouter);
SO i have an express app that I have been building an app that uses a body parser that works with my entire app client side. ( receive post req data )
but app.use(bodyParser.json()); seemed to cause issues with apis which is why i commented it out. now that I dont use it, i cant receive post data from my website.. What should I do so that apis and my website works?
// APP
var app = express();
//app.use(bodyParser.json()); //ISSUE: this is breaks API post //but i need it to recieve MY post req data
app.use(bodyParser.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
A simple kludge would be to define the routes that twilio uses before you activate the bodyParser middleware. Without knowing more about why exactly the bodyparser prevents twilio from working, that's the best I can do.
In generell I alway suggest to not register body parsers globally for all follow up routes, but directly with the route or only locally for one router (path prefix) where it is required.
Moving the routers of twilio before registering the bodyParser for all following routes will also work, but it is less maintainable.
So if you need json data in on specific route, then write it that way:
app.post('/some/route', bodyParser.json(), (req, res, next) => {
// processing of your json
});
The reason why I suggest this is, because the body that is submitted to the server is provided as stream. Whenever you register a middleware that will process the body then it will consume the whole content, and you cannot use any other middleware that will also process the body after that. Using it only for the route where you need this parser eliminates this problem, and allows you to use different body parsers depending on the route.
The larger your project becomes the more likely it is that you come to a situation where you need an other body parsers, then you will be most likely at a point where moving the routes would not work anymore.
var express = require('express');
var app = express();
var path = require('path');
var api = require('./api');
app.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/index.html'));
})
app.listen(8080)
console.log('Server Running');
I know that we are requiring the express module. We are using the express function, we are requiring the module path and storing the reference in variable path and doing the same with api but beyond that I am a little lost. If I wanted to connect to twitter API how would I go about doing this? Can someone please explain the logic behind it so i can go learn this better and apply it by myself with different API's? I sincerely and greatly appreciate all of your help!
Express is a framework for organising your web application server. You open up certain API's routes to listen on the path and respond to the requests when necessary.
You can open API's only for internal use, i.e. calls from the browser running your app. Or you can expose your API to outer world (for example twitter API is doing that).
To connect to twitter API you need to make an outgoing request from your webserver. There are many ways to go about that, starting from native nodeJS package http https://nodejs.org/api/http.html to much more popular alternative request https://github.com/request/request
One thing to note here is that NodeJS web server are in general less restrictive than other language servers, especially when it comes to organising your app and code architecture. Hence more issues for beginners. Feel free to ask more questions.
Main purpose of app in
var app = express()
is to listen to routes (it is as well used to render pages, adding middleware etc.) and only that.
So assume u have a button on your UI which allows you to connect to twitter API. So on the click you make a GET request to your own server, to /api/twitter/connect .
On your server you listen on this path as follows:
var request = require('request'); //assuming you installed this module
app.get('/api/twitter/connect', function(req, res){
request(TWITTER_API_URL + API_KEYS, function(err, body){
res.json(body); //res is the response object, and it passes info back to client side
});
});
You can use "request" package to send requests. But in case of Cross-Origin-Request you must use "HTTPS" instead of "HTTP". You can configure Your request according to your request type like this..
//Load the request module
var request = require('request');
//Lets configure and request
request({
url: 'https://example.com/abc/demo', //URL to hit
qs: {from: 'example', time: +new Date()}, //Query string data
method: 'GET', // specify the request type
headers: { // speciyfy the headers
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
},
body: 'Hello Hello! String body!' //Set the body as a string
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
Besides this there are others way to do the same. And for twitter you can also checkout the module called "twitter"
I'm working on javascript Single Page Application with Aurelia framework and using simple fake backend(express.js) for prototyping purposes.
Backend runs on localhost:8081 and client app on localhost:9000
There are some Cross Domain issues because these are different ports, and adding cross origin headers to the backend seems cumbersome to me.
What i want is simple dispatcher/proxy that would run on, say, localhost:3000 and redirect incoming calls in this manner (localhost:3000/app => localhost:9000) (localhost:3000/api => localhost:8081) Thus eliminating cross domain issues.
I'm looking for really simple solution, maybe there is some node.js app that suited just for such cases.
If you are using Express, you can add this routes to your app.
You need to install the module 'request' for this example
// At the top
var request = require('request');
And then:
//APP
app.use('/app', function (req, res) { request('http://localhost:9000' + req.originalUrl).pipe(res); });
//API
app.use('/api', function (req, res) { request('http://localhost:8081' + req.originalUrl).pipe(res); });
I am writing a library for a web service in Node.js. My library needs to handle all HTTP requests with a particular URL prefix (Eg, /_docs/*).
I want people to be able to use my library without changing much of their code.
The API should look something like this:
server = http.createServer(function(req, res) { ... });
...
myLibrary.listen(server, '_docs/');
or
server = new http.Server();
myLibrary.listen(server, '_docs/');
server.on('request', function(req, res) { ... });
If I merely register another event handler on the server object, the user's http request handler will be called on all HTTP requests as well. My code will race with the user's 404 handler.
Socket.io has a similar problem, and they solve it by making their .listen() function move all existing http request handlers into a private array. When HTTP requests come in, if their code doesn't handle the URL it calls the listeners in the array. However, as far as I can tell this wouldn't work in the second example I've shown above.
Whats the best way to make this work?
What about Connect? Router middleware provides rich Sinatra / Express-like routing.
Example
connect.router(function(app){
app.get('/user/:id', function(req, res, next){
// populates req.params.id
});
app.put('/user/:id', function(req, res, next){
// populates req.params.id
});
})
For advanced use look at http://expressjs.com/guide.html#routing.