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); });
Related
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 :)
I need to build a simple web front-end which will be mostly used to plot some data fetched from a database. The database (namely, InfluxDB) exposes a HTML API which I could just conveniently call directly from my Javascript front-end. I'm putting login service in front of it (AWS Cognito).
However, once a user logs in, they can easily discover my API endpoints in the client-side code, and therefore make arbitrary queries and possibly abuse it or just steal all my data. How can I avoid it? Is it possible to somehow make the API accessible only to the app's front-end? If not, what is the best practice I should follow here?
I'd suggest maybe creating a Node.js based webservice that would wrap your REST API. Using the Express module it's only a few lines to put together a simple REST service and call out to other APIs.
const request = require('request');
const express = require('express');
const app = express();
app.get("/test", function(req, res, next){
res.status(200).send('Hello World');
});
app.get("/testapi", function(req, res, next){
// Read from another API and return result...
var options = {
url: "https://httpbin.org/ip",
method: "get"
};
request(options, function (error, response, body) {
if (error) {
console.error('error:', error);
res.status(500).send(error.message);
} else {
res.status(200).send(body);
}
});
});
let port = process.env.PORT || 3000;
app.listen(port);
console.log(`Express listening on ${port}..`);
If your InfluxDB is also running on EC2, the fastest and safest approach would be to only allow your web application access to the influxdb instance by limiting it in the security group.
Image that your webapp is running on the default VPC with CIDR 172.31.0.0/16 and that influxdb is running on port 8086. Then simply create a security group with an INBOUND rule that port 8086 can only be reached from inside your AWS account (So IP 172.31.0.0/16) and attach it to your Influx EC2 instance. make sure other inbound rules allowing access to 0.0.0.0/0 are removed.
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 running a node.js express 3 server with no proxies and using SSL.
I'm trying to figure out how to force all connections to go through https.
Google searching shows me this:
https://groups.google.com/forum/#!topic/express-js/Bm6yozgoDSY
There's currently no way to force https redirects, though that seems
like a bit of a strange work-around. We have an https-only app and we
just have a simple ~4 line node http server that redirects, nothing
fancy
Which is what I need, but he doesn't say what those 4 lines are.
How do we do this? Thanks.
I don't really understand the point in starting two servers when only one can do the job perfectly. For example, by adding a simple middleware in your server file:
app.use(function(req, res, next) {
if(!req.secure) {
return res.redirect(['https://', req.get('Host'), req.url].join(''));
}
next();
});
This will redirect any non-secure request to the corresponding HTTPS page. For example, http://example.com/ to https://example.com/ and http://example.com/foo?bar=woo to https://example.com/foo?bar=woo. This is definitely the behavior I would expect. Maybe you should filter this by host, so it redirects only on domains for which you own and installed a proper certificate.
If your app is running behind another server like Nginx, you may want to add the configuration parameter app.set('trust proxy', true). Or, even better, make Nginx do the redirect itself, which will be more efficient than any Node.js app.
Edit: According to my benchmarks, join is a little faster than + for concatenating strings. Nothing dramatic, but every win is a win...
You should create a second server listening on 80 and redirect with a 301 header to your https server:
var express = require('express');
var app = express();
app.get('/', function(req, res, next){
res.redirect('https://' + app.address().address)
});
app.listen(80);
I had a similar problem and the redirect solution is not suitable for me because essentially I want to get rid of the browser's insecure warning,
So instead of redirect every message, I did:
app1 = new express()
app1.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/redirect.html'));
});
app1.listen(80, function(){'redirect server running on 80 port'})
and in the redirect.html is just a redirecting html file:
<meta http-equiv="refresh" content="0; URL='https://my-site.com'" />
Of course, this won't work for complicated cases when you want to redirect all routings, but for me, I only want to redirect my homepage to my https homepage and get rid of the browser's insecure warning. Hope this help somebody!
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.