Combine node.js rest api's and angular on same server - node.js

We first developed REST api's using node.js and have that running on a VPS. We now have developed an Angular web app to display data that comes in via a mobile app that calls some of the REST api's and then updates the data by calls back to other REST API's. Running the Angular app on the localhost was able to successfully call the REST api's.
We want to combine both applications on the same server. After searching around it seemed that we could add commands to the REST api server.js to pass urls that didn't meet the REST api path to Angular. Code snippet is below:
// API verison
var apiVersion = '/v1'
var fs ;
var https ;
// Dependencies
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// MongoDB
...
// Express
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Routes
app.use(apiVersion, require('./routes/api'));
// Start server
fs = require('fs')
https = require('https')
https.createServer({
key: fs.readFileSync('...'),
cert: fs.readFileSync('...')
}, app)
.listen(443, function () {
console.log('HTTPS Server running on default port 443')
});
// Pass request to angular?
app.use(function(req, res) {
var path = require('path');
res.sendfile(path.resolve('/home/.../index.html')); // but not getting anything
});
The REST api's still work but when directing a browser to 'mydomain.net' I just get a blank page. I don't see any errors on the node/error logs.
Any ideas?

You can do something like this. Use static content to send from the dist folder and rest will work fine. I have added two reference in case you might need them to refer.
var apiVersion = '/v1'
const fs = require('fs')
const https = require('https');
const path = require('path')
// Dependencies
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
// MongoDB
...
// Express
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Pass request to angular?
app.use('path', express.static(path.resolve('your path should be correct')));
// Routes
app.use(apiVersion, require('./routes/api'));
// Start server
https.createServer({
key: fs.readFileSync('...'),
cert: fs.readFileSync('...')
}, app)
.listen(443, function () {
console.log('HTTPS Server running on default port 443')
});
Check here1 or here2 for more details, there are simple steps to follow.

Related

Why ECONNRESET error is coming in POSTMAN while making a NODEJS request

I have written a simple request response code in NODEJS but there is no response in return of the request is there .
The code for my app.js(Server file) is
const express = require('express');
const cors = require('cors')
const paymentroute = require('./routes/paymentRoutes');
const app = express();
app.use(cors);
app.use("/api",paymentroute);
app.listen(3100,()=>{
console.log(`listening to port 3100`);
})
The code for my req and res is
const express = require('express');
const router = express.Router();
// const { checkout } = require('../controllers/paymentController');
router.post("/checkout",(req,res) => {
console.log("this function is called ")
return res.json({success:"true"})
});
module.exports = router;
Even the console.log inside the res function is not working.
Just change app.use(cors); to app.use(cors());
const express = require('express');
const cors = require('cors');
const paymentroute = require('./routes/paymentRoutes');
const app = express();
app.use(cors());
app.use('/api', paymentroute);
app.listen(3100, () => {
console.log(`listening to port 3100`);
});
I think it is a connection-related issue often related to a networking issue caused by a Virtual Private Network (VPN) that in some cases is required by some API services or, in other cases, prevents you to reach an API service.
The issue seems to be a combo of having the no-cache header enabled and a request URL length over 64 characters. If the issue persists after doing this solution then try to upgrade to the latest version of Postman.

Problem with ssl comuniction with post request

Hey, I built ssl communication with self certificate. The connection is working, but when I trying to deliver data on the client side with post request in postman or my android client, the body of the request in the server side is empty.
Here is my nodejs server code below,thankes for help.
const express = require('express')
const https = require('https')
const path = require('path')
const fs = require('fs')
const app = express()
app.use(express.json())
app.post('/',(req,res,next)=>
{
console.log("we got new connection")
var data =req.body
res.send(data)
})
const ssl_server = https.createServer(
{
key:fs.readFileSync(path.join(__dirname,'cert','key.pem')),
cert:fs.readFileSync(path.join(__dirname,'cert','cert.pem'))
},app)
ssl_server.listen(3443,console.log("SSl server is online!"))
You're reading the response body. You should look at the request.
In any case, there won't probably be much reasonable data to read unless you parse the POST payload somehow; I'd recommend the Express library rather than raw Node.js HTTP bits if you don't want to do that yourself.
here is my answer for my question,like AKS said, you need to parse the post request, i add bodyparser to my code and it worked.
const express = require('express')
const https = require('https')
const path = require('path')
const fs = require('fs')
const bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.urlencoded({ extended: true })) // <==== parse request body as JSON
app.post('/',(req,res,next)=>
{
console.log("we got new connection")
var data =req.body
res.send(data)
})
const ssl_server = https.createServer(
{
key:fs.readFileSync(path.join(__dirname,'cert','key.pem')),
cert:fs.readFileSync(path.join(__dirname,'cert','cert.pem'))
},app)
ssl_server.listen(3443,console.log("SSl server is online!"))

node and express error "cannot GET /" even after I included app.get() in my server.js

I am trying to start my project via launching server.js but I am getting error:"cannot GET /"
even after I made an app.get() route in my server.js
I am using also "body-parser" as a middleware, and "cors"
server.js:
// Setup empty JS object to act as endpoint for all routes
const projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder
app.use(express.static('views'));
const port = 8080;
app.use(express.static('dist'));
// Setup Server
const server=app.listen(port, ()=>{console.log(`running on localhost: ${port}`)});
app.get('/all', sendData);
function sendData (request, response) {
response.send(projectData);
};
// TODO-ROUTES!
app.post('/add', Info);
function Info(req, res) {
projectData['date'] = req.body.date;
projectData['temp'] = req.body.temp;
projectData['content'] = req.body.content;
res.send(projectData);
}
module.exports = server;
I made a POST request to /add and it works. Then I call GET /all and also work. The error cannot GET / is because you are requesting an endpoint that not exists.
Just add a dummy data to your Fn() if you want to see some output on GET request wihtout making any post request
Here is my solution
app.get('/', (req, res) => {
res.redirect('/all');
})
we need this because you do not have any root URL set, so we set the root URL to redirect to /all
2nd step then we add a dummy data in the projectData
var projectData = {
date = new Date().getDate();,
temp = 10,
content="This is Test Content"
}
This way when you call 'http://localhost:8080/' you shall get redirected to http://localhost:8080/all and instead of empty {} you shall see the dummy data.

Enabling SSL certificate on Mongo using Mongoose and Express

I can't figure out how to add an SSL certificate to my server.js so I can access my API on the server through https.
var express = require('express'),
cors = require('cors'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Task = require('./api/models/todoListModel'), //created model loading here
bodyParser = require('body-parser'),
helmet = require('helmet');
// Test SSL connection
var MongoClient = require('mongodb').MongoClient;
// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Tododb'); // was tododb
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// adding Helmet to enhance your API's security
app.use(helmet());
// enabling CORS for all requests
app.use(cors());
app.get('/', (req, res) => res.send('Hello World!'))
var routes = require('./api/routes/todoListRoutes'); //importing route
routes(app); //register the route
app.listen(port);
console.log('Supporter RESTful API server started on: ' + port);
I have tried mongoose.connect('mongodb://localhost/Tododb&ssl=true'); but I don't really know what to do after that? I understand I have to add a reference to the key and certificate files that I have generated but I can't figure how I add those to the connection string.
I have been attempting to follow some of this https://docs.mongodb.com/manual/reference/connection-string/
What's the next step?
The next step is to provide ConnectionOptions to the mongoose.connect call. The mongoose documentation (at https://mongoosejs.com/docs/connections.html#options) specifies that it will pass on ssl specific options to the underlying MongoClient. The options for the MongoClient can be found at: http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect
The ones you are interrested in are likely sslCert, sslKey, and maybe sslPass (along with some more of the ssl* settings). Note that the ones I listed here might require you to load in a file in code yourself. You might be able to use something like:
var fs = require('fs');
var options = {
...
sslCert: fs.readFileSync(path.join(__dirname, <relative path to the cert>))
};
mongoose.connect('mongodb://localhost/Tododb', options);

NodeJs + Unable to access localStorage inside routes.js

In my NODEjs ( using Express ) application, I want to use Country Code inside routes.js but I am unable to access localstorage inside the routes.js
Please provide some solution.
LocalStorage is only available in browsers on the Window object.
The Window object is not available server side.
MDN
Following your comment, you could implement a route in your express application which takes the IP as part of the body.
For this to work you will need body-parser middleware. Example application:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var server;
app.use(bodyParser.json());
app.get('/api/ip', function (req, res) {
res.send(req.body.ip);
});
server = app.listen(3000);
This would return the posted IP.

Resources