I am facing an issue while running the angular and nodejs app which I am trying to integrate with Neo4j app. The issues are the errors that I get-
POST http://localhost:7474/viewNodesStart 404 (Not Found)
and
EXCEPTION: Response with status: 404 Not Found for URL:
http://localhost:7474/viewNodesStart
Though this topic is repetitive in StackOverflow , I am still posting it because the following links suggestions didn't suit my issue.
Angular2 404 Not Found for URL: http://localhost/WebApi2/api/hero
EXCEPTION: Response with status: 404 Not Found for URL / Angular2
https://github.com/johnpapa/angular-tour-of-heroes/issues/94
Please check my code
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Injectable } from '#angular/core';
import { ToasterService } from '../toaster.service';
import { FormGroup, FormControl, FormBuilder, Validators } from '#angular/forms';
import { Http, Response, Headers } from '#angular/http';
import { config } from '../config';
import { Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import { map } from 'rxjs/operators';
import 'rxjs/Rx';
import { Observable } from 'rxjs';
// Statics
import 'rxjs/add/observable/throw';
#Component({
selector: 'app-neo4j-primary',
templateUrl: './neo4j-primary.component.html',
styleUrls: ['./neo4j-primary.component.css']
})
export class Neo4jPrimaryComponent implements OnInit {
constructor(private http: Http, private notify: ToasterService) { }
ngOnInit() {
this.viewNodesStart();
}
emptyObj;
info;
// ------------------------------- Nodes Entire Data --------------
viewNodesStart() {
console.log("INSIDE viewNodesStart()")
// Nodes Value
console.log("inside Nodes Value");
var data = localStorage.getItem('token');
console.log("data is=>",data);
var url = config.url;
var port = config.port;
this.http.post("http://"+url+":"+port+"/viewNodesStart",this.emptyObj)
.map(Response => Response.json())
.subscribe((res: Response) => {
console.log("XXXXXXXXXXXX Response on /viewNodesStart", res);
this.info = res;
console.log('success', this.info.statusCode);
if (this.info.statusCode == 200) {
this.notify.Success("Data added successfully");
} else {
this.notify.Error("Data is not inserted")
}
});
}
}
server.js
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
const neo4j = require('neo4j-driver').v1;
var app = express();
var restify = require('restify');
var expressJwt = require('express-jwt');
var session = require('express-session');
var config = require('./config.json')
app.use(restify.plugins.bodyParser());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(bodyParser.json({
type: 'application/vnd.api+json'
}))
app.use(cors());
app.use(session({
secret: config.secret,
resave: false,
saveUninitialized: true
}));
//*****TM Server ******/
app.use('/viewNodesStart', require('./neo4jserver/tmserver'));
app.get('/', function(req, res) {
res.send('Welcome');
console.log("welcome in console");
});
// start server
var server = app.listen(7473, function() {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
nodeserver.js
// Require Neo4j
var neo4j = require('neo4j-driver').v1;
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var express = require('express');
var router = express.Router();
var app = express();
// Create Driver
const driver = new neo4j.driver("bolt://localhost:11001",neo4j.auth.basic("neo4j", "abc"));
// Run Cypher query
const cypher = 'MATCH (n) RETURN count(n) as count';
//View Engine
app.set('views', path.join(__dirname, 'views'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(express.static(path.join(__dirname, 'public')));
var session = driver.session();
app.post('/', function(req, res) {
console.log("INSIDE NODE JS CONTROLLER OF viewNodesStart");
console.log("BODY IS ", req.body);
var log = JSON.parse(req.body);
console.log(log);
session.run('MATCH (n) RETURN n LIMIT 25').then(function(result) {
result.records.forEach(function(record) {
console.log("record", record);
console.log("result = ", result)
console.log("record._fields[0].properties", record._fields[0].properties);
res.status(200).send({
statusCode: '200',
result: result
});
});
}).catch(function(err) {
console.log(err);
}).then(res=>{
console.log("res.records.length", res.records.length);
}
)
res.send('It Works');
res.send(result);
});
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === "OPTIONS")
res.send(200);
else
next();
}
console.log('Server started on port 11005');
module.exports = router;
module.exports = app;
I guess the problem is with the url you are passing to the http request. You are passing the path of the anuglar route and want to call the node api.
Change the url there to the nodeapi url. Then it will work.
Related
Normally, I use https.createServer method to server my node application over HTTPS, but in this case, I am not sure.
Apparently this is the code,
INDEX.JS
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _config = require('./config/config');
var _config2 = _interopRequireDefault(_config);
var _express = require('./config/express');
var _express2 = _interopRequireDefault(_express);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// config should be imported before importing any other file
var debug = require('debug')('ibs-backend:index');
// make bluebird default Promise
Promise = require('bluebird'); // eslint-disable-line no-global-assign
// module.parent check is required to support mocha watch
// src: https://github.com/mochajs/mocha/issues/1912
if (!module.parent) {
// listen on port config.port
_express2.default.listen(_config2.default.port, function () {
debug('server started on port ' + _config2.default.port + ' (' + _config2.default.env + ')');
});
}
exports.default = _express2.default;
module.exports = exports['default'];
//# sourceMappingURL=index.js.map
config/express.js
import express from 'express';
import expressJwt from 'express-jwt';
import logger from 'morgan';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import compress from 'compression';
import methodOverride from 'method-override';
import cors from 'cors';
import httpStatus from 'http-status';
import expressWinston from 'express-winston';
import expressValidation from 'express-validation';
import helmet from 'helmet';
import winstonInstance from './winston';
import routes from '../server/routes/index.route';
import config from './config';
import APIError from '../server/helpers/APIError';
const app = express();
if (config.env === 'development') {
app.use(logger('dev'));
}
/* Define the routes that work without a JWT token */
const allowedPaths = [
'/api/auth/token',
'/api/auth/token-fan',
'/api/auth/token-celebrity',
'/api/auth/token-host',
'/api/event/get-events-by-admin',
'/api/event/get-current-admin-event'
];
// parse body params and attache them to req.body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressJwt({ secret: config.jwtSecret }).unless({ path: allowedPaths }));
app.use(cookieParser());
app.use(compress());
app.use(methodOverride());
// secure apps by setting various HTTP headers
app.use(helmet());
// enable CORS - Cross Origin Resource Sharing
app.use(cors());
// enable detailed API logging in dev env
if (config.env === 'development') {
expressWinston.requestWhitelist.push('body');
expressWinston.responseWhitelist.push('body');
app.use(expressWinston.logger({
winstonInstance,
meta: true, // optional: log meta data about request (defaults to true)
msg: 'HTTP {{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms',
colorStatus: true // Color the status code (default green, 3XX cyan, 4XX yellow, 5XX red).
}));
}
// mount all routes on /api path
app.use('/api', routes);
// if error is not an instanceOf APIError, convert it.
app.use((err, req, res, next) => {
if (err instanceof expressValidation.ValidationError) {
// validation error contains errors which is an array of error each containing message[]
const unifiedErrorMessage = err.errors.map(error => error.messages.join('. ')).join(' and ');
const error = new APIError(unifiedErrorMessage, err.status, true);
return next(error);
} else if (!(err instanceof APIError)) {
const apiError = new APIError(err.message, err.status, err.isPublic);
return next(apiError);
}
return next(err);
});
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new APIError('API not found', httpStatus.NOT_FOUND);
return next(err);
});
// log error in winston transports except when executing test suite
if (config.env !== 'test') {
app.use(expressWinston.errorLogger({
winstonInstance
}));
}
// error handler, send stacktrace only during development
app.use((err, req, res, next) => // eslint-disable-line no-unused-vars
res.status(err.status).json({
message: err.isPublic ? err.message : httpStatus[err.status],
stack: config.env === 'development' ? err.stack : {}
})
);
export default app;
Normally, I can use letsencrypt ssl with nodejs applications like this
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('Hello!\n');
}).listen(443);
But in this particular scenario, I cant understand, how to do it.
This is the github repository
Thanks for your replies in advance.
You could pass the express app instance to https.createServer(), since express was meant to be used this way.
// We need to import https!
const https = require("https");
// Or, like this
import https from "https";
// Define the key and certificate.
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
// Then...
https.createServer(options, app).listen(443);
It should work the same as any other express app.
Here is a link for more information on that: https://expressjs.com/en/4x/api.html#app.listen
I have fixed this, by installing SSL through Nginx. I have included all certificates in Nginx site configuration and it worked very well.
Thank you for your help.
I have looked at and troubleshot with many different posts on stack overflow of people having similar or the same issue, however, no solutions seem to work for me.
I keep getting the error
Access to XMLHttpRequest at 'http://localhost:3000/email?email=j' from origin 'https://mai...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I thought adding app.use(cors()); would fix it, but the problem persists.
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
var userController = require("./controllers/userController.js");
var emailController = require("./controllers/emailController.js");
var app = express();
app.use(cors());
mongoose.connect(
"redactedForStackOverflow",
{ useUnifiedTopology: true, useNewUrlParser: true },
err => {
if (!err) console.log("MongoDB connection succeeded...");
else
console.log(
"Error in DB connection : " + JSON.stringify(err, undefined, 2)
);
}
);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/", express.static(path.join(__dirname, "angular")));
var port = 3000;
app.listen(process.env.PORT || port, () =>
console.log("Server started at port : " + port)
);
app.use("/users", userController);
app.use("/email", emailController);
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, "angular", "index.html"));
});
module.exports = app;
EDIT
Adding service file
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/operator/toPromise';
import { User } from './user.model';
import { UserComponent } from '../user/user.component';
#Injectable({
providedIn: 'root'
})
export class UserService {
selectedUser: User;
users: User[];
readonly baseURL = 'http://localhost:3000/users';
codeSentIn;
constructor(private http: HttpClient) {}
postUser(users: User) {
const codeOnItsWay = this.codeSentIn;
this.resetCode();
return this.http.post<any>(this.baseURL, {users, codeOnItsWay});
}
resetCode() {
this.codeSentIn = '';
}
getUserList() {
return this.http.get(this.baseURL);
}
getSpecificUser(id) {
return this.http.get<any>(this.baseURL + '/' + id);
}
findPositionInLine(email) {
return this.http.get<any>(this.baseURL + '/positionInLine/' + email);
}
getUserForLogin(email) {
return this.http.get(this.baseURL + '/login/' + email);
}
sendEmailToCheck(emailToCheck) {
return this.http.get('http://localhost:3000/email', { params: { email: emailToCheck }});
}
}
Update: possible missing cors option:
var corsOptions = {
origin: 'localhost:3000',
credentials : true
}
as mentioned from here : Node JS CORS module not setting Access-Control-Allow-Credentials header
Alternatively, Remove app.use(cors());
You can manually add header in all your requests :
app.use((req, res,next) => {
res.set('Access-Control-Allow-Origin', '*');
next();
});
Just add the above code block before
app.use("/users", userController);
app.use("/email", emailController);
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, "angular", "index.html"));
});
I've just started programming in Node and Angular and I'm trying to run a simple application wherein I'm connecting my backend (localhost:3000) to my frontend and displaying the data. If the data I receive from the server when a get request is made is put in a .json file and I access it in the same folder then the data is being displayed.
But if I use the address of the api(http://localhost:3000/purchase) from which the data has been picked I get an undefined error in the browser.
This is the error it shows in the browser:
ContactsComponent.html:2 ERROR TypeError: Cannot read property 'Empno' of undefined
at Object.eval [as updateRenderer] (ContactsComponent.html:2)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:22503)
at checkAndUpdateView (core.js:21878)
at callViewAction (core.js:22114)
at execComponentViewsAction (core.js:22056)
at checkAndUpdateView (core.js:21879)
at callViewAction (core.js:22114)
at execComponentViewsAction (core.js:22056)
at checkAndUpdateView (core.js:21879)
at callWithDebugContext (core.js:22767)
This is the Output from my server (http://localhost:3000/purchase) on Postman:
{
"Empno": "113 ",
"Ename": "Mary ",
"Sal": "15220 ",
"Deptno": "DP "
}
This is the code in angular for the service:
import { Injectable } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpClient } from '#angular/common/http';
import 'rxjs/add/operator/map';
import { map, filter, switchMap, catchError } from 'rxjs/operators';
import { Contact } from './contact';
import { HttpErrorResponse, HttpResponse } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class ContactService {
contact: Contact[];
// configUrl1 = '../assets/test.json';
configUrl1 = 'http://localhost:3000';
constructor(private http: HttpClient) { }
// retrieving contacts
getPurchase() {
return this.http.get(this.configUrl1);
}
}
**This is the code for the Component:**
import { Component, OnInit } from '#angular/core';
import { ContactService } from '../contact.service';
import { Contact } from '../contact';
#Component({
selector: 'app-contacts',
templateUrl: './contacts.component.html',
styleUrls: ['./contacts.component.scss'],
providers: [ContactService]
})
export class ContactsComponent implements OnInit {
contact: Contact;
Empno: string;
Ename: string;
Sal: string;
Deptno: string;
constructor(private contactService: ContactService) { }
ngOnInit() {
this.contactService.getPurchase()
.subscribe((data: Contact) => this.contact = {...data});
}
}
This is the code for defining the structure for contact:
export class Contact {
Empno: string;
Ename: string;
Sal: string;
Deptno: string;
}
This is the code for the HTML file of the contact component:
<div class= "container">
<p>Its Working here also</p>
{{contact.Empno}}
{{contact.Ename}}
</div>
Server Side code:
App.js
//importing modules
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var mssql = require('mssql');
var path = require('path');
var app = express();
const route = require('./routes/route');
//port no
const port = 3000;
// adding middlewear - cors
app.use(cors());
// adding middlewear - bodyparser
// app.use(bodyparser.json());
// static files
app.use(express.static(path.join(__dirname, 'public')));
//creating routes
app.use('/purchase', route);
//testing
app.get('/', (req,res)=>{
res.send('foobar');
});
// //bind the port
app.listen(port, () => {
console.log('Server started at port: ' + port);
});
// create application/json parser
var jsonParser = bodyParser.json()
// app.use(bodyParser.json({ type: 'application/*+json' }))
// POST /login gets urlencoded bodies
app.post('/login', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
route.js
const express = require('express');
const router = express.Router();
var bodyParser = require('body-parser');
var app = express();
const sql = require('mssql');
const config = 'mssql://vpn:vpn1#ASPL-AVG:1433/Sampledb';
app.use(bodyParser.json());
var jsonParser = bodyParser.json()
router.get('/', jsonParser,(req,res, next)=>{
var conn = new sql.ConnectionPool(config);
conn.connect().then((conn) => {
var sqlreq = new sql.Request(conn);
sqlreq.execute('SelEmpl10', function(err, recordset) {
res.json(recordset.recordsets[0][1]);
console.log(recordset.recordsets[0][1]);
})
})
});
//add purchase order
router.post('/' , jsonParser ,(req, res, next) => {
//logic to add record
console.log(req.body.username);
var conn = new sql.ConnectionPool(config);
conn.connect().then((conn) => {
var sqlreq = new sql.Request(conn);
sqlreq.input('Username', sql.VarChar(30), req.body.username);
sqlreq.input('Password', sql.VarChar(30), req.body.password);
sqlreq.input('Email', sql.VarChar(30), req.body.email);
sqlreq.input('Name', sql.VarChar(30), req.body.name);
sqlreq.execute('saveuser').then(function(err, recordsets, returnValue, affected) {
console.dir(recordsets);
console.dir(err);
conn.close();
}).catch(function(err) {
res.json({msg: 'Failed to add contact'});
console.log(err);
});
});
})
//delete purchase order
router.delete('/:id', (req, res, next) => {
//logic to delete record
});
module.exports = router;
The data received from SQL is this:
{
"recordsets": [
[
{
"Empno": "112 ",
"Ename": "john ",
"Sal": "142500 ",
"Deptno": "CS "
},
{
"Empno": "113 ",
"Ename": "Mary ",
"Sal": "15220 ",
"Deptno": "DP "
}
]
],
"recordset": [
{
"Empno": "112 ",
"Ename": "john ",
"Sal": "142500 ",
"Deptno": "CS "
},
{
"Empno": "113 ",
"Ename": "Mary ",
"Sal": "15220 ",
"Deptno": "DP "
}
],
"output": {},
"rowsAffected": [
2
],
"returnValue": 0
}
After adding the parameters in Node the output is this:
{
"Empno": "113 ",
"Ename": "Mary ",
"Sal": "15220 ",
"Deptno": "DP "
}
The issue is possibly connected to the use of bodyParser. It may be trying to parse already parsed JSON. Basically add the parser once at the top level and remove it from the routes. Also it may be connected to using json() instead of send(). I’ve had issues where if the data had a property named data, it could cause json parse/stringify to fail.
Try the following. In App.js reintroduce the line app.use(bodyParser.json()), this only needs to be added once at a top level location such as this entry file. Also from this file remove jsonParser middleware from the /login POST route:
var bodyParser = require('body-parser');
var app = express();
const route = require('./routes/route');
//port no
const port = 3000;
// adding middlewear - cors
app.use(cors());
// adding middlewear - bodyparser
app.use(bodyParser.json());
// static files
app.use(express.static(path.join(__dirname, 'public')));
//creating routes
app.use('/purchase', route);
//testing
app.get('/', (req,res)=>{
res.send('foobar');
});
// //bind the port
app.listen(port, () => {
console.log('Server started at port: ' + port);
});
// POST /login gets urlencoded bodies
app.post('/login', function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
In route.js, remove the bodyParser.json() and jsonParser middleware, it's already included at the top level as app.use(bodyParser.json()); applies it to all routes/verbs:
const express = require('express');
const router = express.Router();
var app = express();
const sql = require('mssql');
const config = 'mssql://vpn:vpn1#ASPL-AVG:1433/Sampledb';
router.get('/',(req, res, next)=>{
var conn = new sql.ConnectionPool(config);
conn.connect().then((conn) => {
var sqlreq = new sql.Request(conn);
sqlreq.execute('SelEmpl10', function(err, recordset) {
res.json(recordset.recordsets[0][1]);
console.log(recordset.recordsets[0][1]);
})
})
});
//add purchase order
router.post('/', (req, res, next) => {
//logic to add record
console.log(req.body.username);
var conn = new sql.ConnectionPool(config);
conn.connect().then((conn) => {
var sqlreq = new sql.Request(conn);
sqlreq.input('Username', sql.VarChar(30), req.body.username);
sqlreq.input('Password', sql.VarChar(30), req.body.password);
sqlreq.input('Email', sql.VarChar(30), req.body.email);
sqlreq.input('Name', sql.VarChar(30), req.body.name);
sqlreq.execute('saveuser').then(function(err, recordsets, returnValue, affected) {
console.dir(recordsets);
console.dir(err);
conn.close();
}).catch(function(err) {
res.json({msg: 'Failed to add contact'});
console.log(err);
});
});
})
// delete purchase order
router.delete('/:id', (req, res, next) => {
//logic to delete record
});
module.exports = router;
If that still fails, try just using res.send() instead of res.json(), even just for troubleshooting purposes.
The last thing that I'd recommend is sending an actual error or at least some type of 4xx or 5xx status code so that Angular HttpClient can treat it as an actual error instead of a successful HTTP request with a 200 status code.
Hopefully that helps!
Add a safe navigation operation to the contact variable.
<div class= "container">
<p>Its Working here also</p>
{{contact?.Empno}}
{{contact?.Ename}}
</div>
which is equivalent to contact != null ? contact.Empno: null
Update:
Also, add Error Handling code:
ngOnInit() {
this.contactService.getPurchase().subscribe(
(data: Contact) => {
this.contact = {...data};
},
error => {
console.log("Error Occured: "+ error);
}
);
}
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);
});
});
}
I'm I'm stuck in post request while I'm developing upload images in quill editor.
I have no idea what I have to do to fix this issue.
When I try to send data using post request, then 404 error occur.
routes/img.js - UPDATED
var ImageFile = require('../models/imageFiles');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'img/') // Set directory
},
filename: function (req, file, cb) {
cb(null, file.name) // Set file name
}
});
var img = multer({ storage: storage });
router.post('/upload', img.single('imgfile'), (req, res, next) => {
var imageFile = new ImageFile({
name: req.body.name,
type: req.body.type,
size: req.body.size,
content: req.body.content
});
imageFile.save((err, result) => {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
res.status(201).json({
message: 'User created',
obj: result
});
});
});
module.exports = router;
app.js
const express = require('express');
var bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var appRoutes = require('./routes/app');
var userRoutes = require('./routes/user');
var imgRoutes = require('./routes/img');
var app = express();
// Start
app.use(express.static(path.join(__dirname, '../awesome-drill/dist')));
app.use(logger('dev'));
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-Width, Content-Type, Accept');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
next();
});
app.use('/user', userRoutes);
app.use('/img', imgRoutes);
app.use('/', appRoutes);
app.use(express.static('routes'));
// It's for routing SPA
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../awesome-drill/dist/index.html'));
});
app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
frontside service (angular4)
import { Injectable } from '#angular/core';
import {Http, Headers, Response} from '#angular/http';
#Injectable()
export class FileService {
public userId = localStorage.getItem('userId');
constructor(private http: Http) { }
imgUpload(obj) {
const body = JSON.stringify(obj);
const headers = new Headers({
'Content-Type': 'application/json'
});
return this.http.post('img/upload', body, {
headers: headers
})
.map((response: Response) => response.json());
}
}
Thanks to you, I found my mistake and I added it. However, 404 error still occur.
It's my folder structure.
You aren't exporting your router. Add the following to the end of your routes/img.js file.
module.exports = router;
The way you have it now, there is no default export, so when you require('./routes/img') you're importing nothing. If you were to console.log(imgRoutes) in app.js it would probably return undefined.