I have a MEAN application that needs deployment and I chose to deploy it on AWS Linux AMI but I have some problems deploying it.
Based on the tutorials I read so far every nodejs and express contains html pages.
How do I deploy it without html pages on it? like if they go to the domain they just see a blank page?
I know I can just empty an html file but I any other solutions?
here's my server.js
const http = require("http");
const debug = require("debug")("sales-and-inventory");
const app = require("./app");
// normalizePort() makes sure that the port is a valid number data type
const normalizePort = val => {
var port = parseInt(val, 10);
if (isNaN(port)) {
// isNot-a-Number
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
};
// checks the type of error occured
const onError = error => {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
};
// just logging
const onListening = () => {
const addr = server.address();
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
debug("Listening on " + bind);
};
// set a config for the express environment & config for the port
const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);
const server = http.createServer(app);
// registered on this listeners on the function above
server.on("error", onError);
server.on("listening", onListening);
// start server
server.listen(port);
here's the app.js
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const authRoutes = require("../routes/auth.route");
const userRoutes = require("../routes/user.route");
const customerRoutes = require("../routes/customer.route");
const vendorRoutes = require("../routes/vendor.route");
const salesRoutes = require("../routes/sales-order.route");
const purchaseRoutes = require("../routes/purchase-order.route");
const inventoryRoutes = require("../routes/inventory.route");
const transferRoutes = require("../routes/transfer.route");
const paymentRoutes = require("../routes/payment.route");
const app = express();
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
mongoose.connect(process.env.ATLAS_CONNECTION_STRING, { useNewUrlParser: true })
.then(() => {
console.log("Connected to Atlas");
})
.catch(err => {
if (err) {
console.log(err);
}
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// CORS
app.use((req, res, next) => {
// allows any domain to access our resources
res.setHeader("Access-Control-Allow-Origin", "*");
// allows domain with a certain set of headers
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
// allows http type of requests
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
res.header('Content-Security-Policy', 'img-src "self"');
next();
});
app.use("/api/auth", authRoutes);
app.use("/api/user", userRoutes);
app.use("/api/customer", customerRoutes);
app.use("/api/vendor", vendorRoutes);
app.use("/api/sales", salesRoutes);
app.use("/api/purchase", purchaseRoutes);
app.use("/api/inventory", inventoryRoutes);
app.use("/api/transfer", transferRoutes);
app.use("/api/payment", paymentRoutes);
module.exports = app;
After launching the EC2 Instance, you can go ahead with the setting SSH on your machine if you are using windows go for PUTTY.
Follow this tutorial for deploying NodeJS Application once you are logged into instance.
https://www.youtube.com/watch?v=tasoWTGM1hA
before deploying Make sure add Security group to EC2 instance and add the role of HTTP, HTTPS with any IP address I mean 0.0.0.0 and any port :0
Related
I have created a site using Create React App on the frontend and Node express on the back. I then hosted React on IIS and ran Node as a windows service on the backend.
When running the app I set my callback paths in React (REACT_APP_HOST) to "localhost" and in the node my routes are "/routeName". This being said, the first path called is ${REACT_APP_HOST}/sitemap and the receiving path on the server is router.use('/siteMap', (req, res, next) => siteMapController(req, res, next));.
On the local server, using it as a client, this works perfectly. On a remote client (same domain) I am getting a 404 error.
The next step I tried was changing REACT_APP_HOST to "", making the resulting call to "/sitemap". This has stopped the functioning even on localhost.
Here is my code (app.js, sitemap fetch and server.js). Hoping that someone can give me a clue as to where I am going wrong.
//app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser')
var logger = require('morgan');
var cors = require('cors');
var nodeSSPI = require('express-node-sspi');
let routeList = require('./routes/routeList');
let FileLoader = require('./Controllers/FileLoader');
var app = express();
app.use(bodyParser.json({ limit: '400000' }));
app.use(cors({
origin:['http://localhost', 'http://intranet-test', 'http://intranet'],
credentials: true
}));
app.use(express.static(path.join(__dirname,'../public')));
app.options('*', cors()); // include before other routes
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
//https://www.npmjs.com/package/yarn
app.use(nodeSSPI({
retrieveGroups: false,
offerBasic: false,
authoritative: true,
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
routeList(app);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log(req.originalUrl);
console.log(req.method)
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
console.log(err);
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
//sitemap fetch
export const fetchInit = () => {
return ({
method: 'GET'
, headers: {
'Content-Type': 'application/json'
}
, credentials: 'include'
})
};
export const Sitemap_Fetch = () => (dispatch) => {
dispatch({
type: ActionTypes.SITEMAP_LOADING
});
var myReq = new Request(`${process.env.REACT_APP_HOST}/siteMap`, fetchInit());//?' + params
return fetch(myReq)
.then((response) => {
// if (response.ok) {
return response;
// }
// else {
// var error = new Error("Error " + response.statusText);
// error.response = response;
// throw error;
// }
},
(error) => {
var err = new Error(error.message);
throw err;
}
)
.then(response => response.json())
.then((data) => {
try {
dispatch({
type: ActionTypes.SITEMAP_LOADED,
payload: data
})
return data;
}
catch (ex) { throw ex }
})
.catch((err) => {
return dispatch({
type: ActionTypes.SITEMAP_FAILED,
payload: err.message
})
});
}
//server.js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('./app');
var debug = require('debug')('node-backend:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort('3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, '0.0.0.0');
server.on('error', onError);
server.on('listening', onListening);
server.on('request',test=>{console.log(test)})
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
console.log(addr)
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
console.log('Listening on ' + bind);
}
Finally I am adding the .env file from my React site
BROWSER=none
SKIP_PREFLIGHT_CHECK=true
REACT_APP_HOST=http://localhost
PORT=80
This works as is. When I change REACT_APP_HOST to nothing it stops functioning.
THanks.
What I have done to solve this is use the serve (https://stackoverflow.com/a/49209041/2242131) command from a simple batch file and run my node backend from another batch. Then in React I created a constant called "hostname" which I set to ${window.location.hostname}:3000. This is now consistently serving my pages the necessary data.
I have 2 server.js files. One of them is inside the backend folder where when I run nodemon server.js on localhost:3000. And I'll start angular with ng serve inside the angular folder and login to my app no problem. Everything works. No CORS issue.
BUT
If I try to run my server.js file in the root directory where express serves my angular build folder. It starts up on localhost:8080, but when I try to login to my app, I get
inside my app.js file I have the following, which should be relevant. Another thing worth noting
is I made a docker version and that version gives me the CORS error too. So it seems to only work when running locally with ng serve and nodemon server.js
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.header(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
server.js file in backend folder (localhost:3000 No CORS error)
const app = require("./app");
const debug = require("debug")("node-angular");
const http = require("http");
const mongoose = require("mongoose");
var redis = require("redis");
var env = require("dotenv").config();
const normalizePort = val => {
var port = parseInt(val, 10);
if (isNaN(port)) {
e;
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
};
const onError = error => {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);
mongoose
.connect(
"mongodb://" +
process.env.COSMOSDB_HOST +
":" +
process.env.COSMOSDB_PORT +
"/" +
process.env.COSMOSDB_DBNAME +
"?ssl=true&replicaSet=globaldb",
{
auth: {
user: process.env.COSMODDB_USER,
password: process.env.COSMOSDB_PASSWORD
}
}
)
.then(() => console.log("Connection to CosmosDB successful"))
.catch(err => console.error(err));
const onListening = () => {
const addr = server.address();
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
debug("Listening on " + bind);
};
const port = normalizePort(process.env.PORT || "3000");
app.set("port", process.env.PORT || port);
var server = app.listen(app.get("port"), function() {
debug("Express server listening on port " + server.address().port);
});
server.js in root directory (localhost:8080 CORS error)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
const userRoutes = require("./app/routes/user");
const appRoutes = require("./app/app");
const cors = require("cors");
app.use(morgan('dev'));
app.use(cors({ origin: 'http://localhost:8080' , credentials : true}));var mongoose = require('mongoose');
var path = require('path');
var config = 'mongodb://azure45:azure45#ds133321.mlab.com:33321/azure_chat'
//const app = require("./app");
const debug = require("debug")("node-angular");
var env = require("dotenv").config();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
next();
});
mongoose
.connect(
"mongodb://" +
process.env.COSMOSDB_HOST +
":" +
process.env.COSMOSDB_PORT +
"/" +
process.env.COSMOSDB_DBNAME +
"?ssl=true&replicaSet=globaldb",
{
auth: {
user: process.env.COSMODDB_USER,
password: process.env.COSMOSDB_PASSWORD
}
}
)
.then(() => console.log("Connection to CosmosDB successful"))
.catch(err => console.error(err));
app.use(express.static(__dirname + '/public/dist/glass/'));
//var apiRoutes = require('./app/app')(app, express);
app.use("/api/", appRoutes);
app.use("/api/user", userRoutes);
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/dist/glass/index.html'));
});
app.listen(8080);
console.log('Magic happens on port ' + 8080);
const normalizePort = val => {
var port = parseInt(val, 10);
if (isNaN(port)) {
e;
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
};
const onError = error => {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);
const onListening = () => {
const addr = server.address();
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
debug("Listening on " + bind);
};
Here's the project file structure as a reference. app.js is where all my APIs are.
Try to use Node.js CORS library for CORS.
Something like below.
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
With reference to rise's answer:
Add options to cors method:
var corsOptions = {
origin: 'your client url',
optionsSuccessStatus: 200,
}
app.use(cors(corsOptions));
I'm using client side ionic with server side node.js + express.js. Currently testing in my local computer.
I am able to do a POST request through postman, however I couldn't make it through ionic.
Research
I have spent almost 1 day to investigate this. But I couldn't find a way to solve this. More over, there is no error on the client nor the server side, thus it is difficult for me to investigate this.
From what I can see, I suspect the error comes from the PREFLIGHT OPTIONS settings. I should set it somewhere in my node + express.
I am using the cors plugin https://www.npmjs.com/package/cors and use the settings to allow PREFLIGHT OPTIONS, however it still does not work.
I looked at the chrome network inspection, this is what I have:
And this is what it looks in the console.
My Client-side Code (Ionic)
postAPI() {
return new Promise ((resolve,reject)=>{
this.http.post("http://localhost:8080/api/status/", {
"body" : "This is the body post"
}, httpOptions).subscribe((val) => {
console.log("POST call successful value returned in body", val);
resolve();
}, error => {
console.log("POST call in error", error);
reject();
}, () => {
console.log("The POST observable is now completed.");
})
})
}
My Server-side Code (Node + Express)
Here, I am using CORS OPTIONS settings to allow all OPTIONS requests.
I am setting it in server.js while the route itself is in status.js.
server.js
const express = require('express'); // call express
const app = express(); // define our app using express
var cors = require('cors'); // setup CORS so can be called by ionic local app
const port = process.env.PORT || 8080; // set our port
// ALLOW CORS
app.use(cors());
// SET CORS for PREFLIGHT OPTIONS
app.options('*', cors());
// Libraries
const bodyParser = require('body-parser');
const admin = require('firebase-admin');
const serviceAccount = require('./serviceAccountKey.json');
// Json
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Firebase Configs
//firebase admin sdk for Firestore
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://menuu-sm-dev.firebaseio.com"
});
var afs = admin.firestore();
var db = afs;
app.set("afs", afs);
var db = admin.firestore();
const settings = {timestampsInSnapshots: true};
db.settings(settings);
app.set("db", db);
// ROUTES
app.use('/api',require('./routers/api/api'));
app.use('/',require('./routers/home'));
// START
app.listen(port);
console.log('Server is served on port ' + port);
api.js
// SETUP
const express = require('express'),
router = express.Router();
const url = require("url");
const path = require("path");
///const sanitizer = require("sanitize")();
// ROUTES (/api/)
router.use('/user',require('./user'));
router.use('/status',require('./status'));
router.use('/timeline',require('./timeline'));
router.use('/photo',require('./photo'));
router.use('/like',require('./like'));
router.use('/comment',require('./comment'));
router.use('/checkin',require('./checkin'));
router.use('/promotion',require('./promotion'));
// OTHERS
module.exports = router;
status.js
// SETUP
const express = require('express'),
router = express.Router();
const url = require("url");
const path = require("path");
const Timeline = require("../../models/Timeline");
const Post = require("../../models/Post");
///const sanitizer = require("sanitize")();
// ROUTES
// ===============================================================
// /status/
var statusRoute = router.route('');
// Create
statusRoute.post((req, res) => {
let query = url.parse(req.url,true).query;
let userKey = query.userkey;
let statusKey = query.statuskey; // ga dipake
let reqBody = req.body;
let db = req.app.get('db');
// ! remember to do sanitizing here later on
if (typeof userKey != 'undefined'){
// Create New Status
let newStatusRef = db.collection('status/'+userKey+'/status').doc();
newStatusRef.set(reqBody);
// Fan-Out
let docId = newStatusRef.id; // get pushed id
//let docId = "1";
// Insert request body to models
var post = new Post();
var timeline = new Timeline();
Object.entries(reqBody).forEach( ([key, value]) => {
timeline.set(key,value);
post.set(key,value);
}
);
// Specify operations to be done
var batch = db.batch();
let newPostRef = db.collection('posts/'+userKey+'/posts').doc(docId);
batch.set(newPostRef, post.data);
console.log("b" + batch);
// Timeline & Commit
getFollowers(userKey, db)
.catch((error) => {
console.error("Error writing document: ", error)
})
.then((followers) => {
// ATTENTION!!
// if followers > 9, batch write supposedly wont work because max limit of batch write is 10
if (followers.length!=0){
followers.forEach((f) => {
let newTimelineRef = db.collection('timeline/'+String(f)+'/timeline').doc(docId);
console.log(typeof batch);
console.log("a" + batch);
batch.set(newTimelineRef, timeline.data);
});
}
// Commit changes
batch.commit()
.then(() => {
console.log("POST Request");
res.json({"Action":"CREATE","Status":"Successful", "User key":userKey, "Post Key": docId, "followers":followers});
})
.catch((error) => {
console.error("Error writing document: ", error)
})
});
}
});
Could you help me find the cause of this issue. Thanks!
Replace app.use('cors') with the below code:
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", '*');
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
I am doing a MEAN stack application. To communicate between the client and the server I use some HTTP requests and websockets.
On the localhost it works fine.
But then, when I try to deploy the application from localhost to a specific server, the websockets are not working anymore. However, http requests work fine.
I got this error:
Firefox can't establish a connection to the server at
ws://138.250.31.29:3000/socket.io/?userId=5b7c030dca40486dabaafaaf&EIO=3&transport=websocket&sid=oEcoYYbhD4ighJC0AAAB.
I didn't succeed to have more information about this error.
In order to establish the connection I have two files on Node.JS:
APP.JS
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const logger = require("morgan");
const favicon = require("serve-favicon");
const cors = require("cors");
require("./models/db");
require("./config/passport");
const passport = require("passport");
const apiRouter = require("./routes/index");
const corsOptions = {
origin: "*",
optionsSuccessStatus: 200
};
const app = express();
app.use(logger("dev"));
app.use(express.json({ limit: "1gb" }));
app.use(express.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(cors(corsOptions));
app.use("/api", apiRouter);
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"
);
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
// error handlers
// Catch unauthorised errors
app.use(function(err, req, res, next) {
if (err.name === "UnauthorizedError") {
res.status(401);
res.json({ message: err.name + ": " + err.message });
}
});
module.exports = app;
WWW
!/usr/bin/env node
/**
* Module dependencies.
*/
const app = require("../app");
const debug = require("debug")("sorfml:server");
const http = require("http");
const socketIO = require("socket.io");
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Bind the socket.IO with the http server
*/
const io = socketIO(server);
io.origins("*:*");
clientsList = {};
/**
* Socket connection
*/
io.on("connection", socket => {
console.log("Client connected " + socket.id);
socket.user_id = socket.handshake.query.userId;
clientsList[socket.handshake.query.userId] = socket;
socket.on("disconnect", () => {
delete clientsList[socket.user_id];
console.log("Client disconnected: " + socket.id);
});
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
const port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "Pipe " + port : "Port " + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
const addr = server.address();
const bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
console.log("Listening on " + bind);
}
On the client side:
import * as io from "socket.io-client";
private socket;
this.socket = io("http://138.250.31.29:3000", { query: "userId=" + userId });
this.socket.on("sendNotification", data => {
// Do a function
});
this.socket.on("deleteNotificationFromAuthor", data => {
// Do a function
});
You are using http instead of ws on client side,
this.socket = io("ws://138.250.31.29:3000", { query: "userId=" + userId });
FYI: In case you didn't knew, both http and ws port may be the same as the w3 standard. You should use ws protocol to create a web socket connection
Hope that helps.
It seems my Node JS or Express is caching the results from MongoDB, this seems to be an advantage for some, but for me it is causing a problem. I don't want the json response to be cached. Please suggest how to stop this.
This is my Server.js if you notice I have used res.headers and app.disable methods to prevent caching.
// set up ======================================================================
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
var server = require('http').Server(app);
var mongoose = require('mongoose'); // mongoose for mongodb
var port = process.env.PORT || 8000; // set the port
var database = require('./config/database'); // load the database config
var morgan = require('morgan');
var methodOverride = require('method-override');
var io = require('socket.io')(server);
var cors = require('cors');
var messageId = {};
// configuration ===============================================================
// Connect to DB
mongoose.connect(database.remoteUrl)
mongoose.Promise = global.Promise;
mongoose.connection.on('error', function(e) {
console.log('Can not connect Error:>>',e);
process.exit();
});
mongoose.connection.once('open', function(d) {
console.log("Successfully connected to the database");
})
//app.use(express.static('./public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Cache-Control", "no-cache, no-store, must-revalidate");
res.header("Pragma", "no-cache");
res.header("Expires", 0);
next();
});
app.disable('view cache');
io.set('origins', '*:*');
http = require('http'),
server = http.createServer(function (req, res) {
//res.writeHead(200,{'content-type':'text/plain'});
// res.write("Sever On");
// res.end();
}),
io = io.listen(server);
io.on('connection', function (socket) {
console.log('User Connected -- Server Online');
socket.on('message', function (msg,msgId) {
io.emit('message', "Hello");
console.log("message from client:", msg);
setInterval(function(){
io.emit("messageStatus",msgId);
},500)
});
});
app.use(require('./app/routes.js'));
app.listen(port);
//server.listen(port);
console.log("App listening on port " + port);
This is my Route.js
var express = require('express')
var app = module.exports = express.Router();
var UserProfile = require('./models/UserProfile');
app.get('/User', function (req, res) {
UserProfile.find({
EmailID: req.query.EmailID
}, function (err, profile) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
return res.json({
"success": false,
"msg": err
})
console.log(err);
}
res.status(200).send(profile)
});
});
This is my provider.js
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class ProfileProvider {
data : any
constructor(public http: Http,) {
}
// public getProfile(EmailID){
// console.log(this.http.get(CONFIG.apiUrl+'User?EmailID='+EmailID).map(response => response.json().result));
// return this.http.get(CONFIG.apiUrl+'User?EmailID='+EmailID).map(response => response.json().result);
// }
public getProfile(EmailID){
console.log("Provider,>>",EmailID)
if (this.data) {
return Promise.resolve(this.data); }
return new Promise(resolve => {
this.http.get('http://192.168.0.100:8000/User?EmailID='+EmailID)
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
}
Now if run this (http://192.168.0.100:8000/User?EmailID=abc#abc.com) on my browser and if I change the email ID, i get different responses. But in the ionic app it some how gives me the same responses even after changing the parameters
And I am using AWS and my MongoDB is hosted there.
Your problem is in the provider. You are caching the results of the api call in the data property.
if (this.data) {
return Promise.resolve(this.data); }
Try always fetching the data:
public getProfile(EmailID){
return new Promise(resolve => {
this.http.get('http://192.168.0.100:8000/User?EmailID='+EmailID)
.map(res => res.json())
.subscribe(data => {
resolve(data);
});
});
}