Angular: Error while fetching data from Node API? - node.js

I am trying to fetch json data from my Nodejs API using URL - localhost:3000/articles/publicationData which is running successfully in Postman app but don't know why is giving error with same url in angular app, but in Angular app it is giving an error -
HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:3000/articles/publicationData", ok: false, …}
error: "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot GET /articles/publicationData</pre>\n</body>\n</html>\n"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:3000/articles/publicationData: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:3000/articles/publicationData"
My app-service.ts file is -
import { Injectable } from '#angular/core';
import { HttpClient} from '#angular/common/http';
import { AppSetting } from './appsetting'
#Injectable({
providedIn: 'root'
})
export class AppServiceService {
private SERVERURL = AppSetting.API;
constructor(private http: HttpClient) { }
login(user){
console.log(user);
return this.http.post<any>(this.SERVERURL+"users",user);
}
getPublication(){
let url = "http://localhost:3000/articles/publicationData";
return this.http.get(url);
}
}
My app.component.ts file
import { Component, OnInit } from '#angular/core';
import { DatepickerModule } from 'ng2-datepicker';
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
import { DatepickerOptions } from 'ng2-datepicker';
import { AppServiceService } from './../app-service.service';
import { Subscriber } from 'rxjs';
#Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
constructor(private http: HttpClient,private auth : AppServiceService, private _router: Router) {
this.auth.getPublication().subscribe(data => {
console.warn(data);
})
}
ngOnInit(): void {
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
}
}
Controller.js
var db = require("../db.js");
var ObjectId = require('mongodb').ObjectID;
var mysql = require('mysql');
var connection = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'name'
});
var publicationData = (req, res) => {
var sql = `select pub_master.PubId, pub_master.Title,
pub_master.MastHead, pub_master.Circulation, pub_master.WebSite,
pub_master.Issn_Num, pub_master.Place, picklist.Name as city
from pub_master
join picklist on picklist.id = pub_master.Place
and picklist.id <> 0`;
connection.query(sql,[], function (error, results, fields) {
if (error) {
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
if(results.length >0){
res.send({
"code":200,
result : results
});
}
else{
res.send({
"code":204,
"success":"Email and password does not match"
});
}
}
});
}
module.exports = {
publicationData: publicationData
}
Publication route
var express = require("express");
var articlescontroller = require("../controller/articlesController")
var articlesrouter = express.Router();
articlesrouter.route('/publicationData')
.post(articlescontroller.publicationData);
app.js
var express = require("express");
const serverless = require('serverless-http');
var moviesrouter = require("./routes/movierouter");
var articlesrouter = require("./routes/articlesrouter");
// var mailarticlerouter = require('./routes/mailarticlerouter');
var bodyParser = require("body-parser");
var mongoos = require("mongoose");
/*****************MYSQL CONNECTION*********************/
var mysql = require('mysql');
var connection = mysql.createPool({
host : '',
user : '',
password : '',
database : ''
});
/************************************* */
mongoos.set("debug", (collectionName, method, query, doc) => {
console.log(JSON.stringify(query));
});
mongoos.Promise = Promise;
var db = mongoos.connect("mongodb+srv://aamadmin:Rix2Jag8#irmpl-zame7.mongodb.net/impact?retryWrites=true&w=majority",{useUnifiedTopology: true,useNewUrlParser:true});
console.log("connected to mongodb");
var app = express();
var cors = require('cors');
const userrouter = require("./routes/userrouter");
app.use(cors());
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();
});
app.use(bodyParser.json());
var server = app.listen(3000,()=>{
console.log("server is running on port 3000");
});
server.timeout = 600000;
module.exports.handler = serverless(app);
app.use('/articles',articlesrouter);

From your Postman screen, you need to send a POST request to localhost:3000/articles/publicationData, not a GET request. You have the 404 error with your code and when trying to access localhost:3000/articles/publicationData in browser because you're sending GET requests.
In your Angular code, change from :
getPublication(){
let url = "http://localhost:3000/articles/publicationData";
return this.http.get(url);
}
to :
getPublication(){
let url = "http://localhost:3000/articles/publicationData";
return this.http.post(url, {});
}

Related

Introducing a express middleware in NodeJS TypeScript OOP

I'm trying to introducing cls-rtracer and when instantiating it, it's coming as undefined.
The code is written in TypeScript using Object Oriented Paradigm instead of Functional.
Examples posted in NPM for the library are functional.
I've commented the place where it is coming as undefined.
Introducing any other middleware in this express app seems straightforward except cls-rtracer
This is the code:
import express, {NextFunction, Response, Request} from 'express';
import * as bodyParser from 'body-parser';
import helmet from 'helmet';
import morgan from 'morgan';
import cors from 'cors';
import swaggerJSDoc from 'swagger-jsdoc';
import swaggerui from 'swagger-ui-express';
import {Controller} from './api/v1/controllers/Controller';
import {logger} from './api/v1/utils/Logger';
import {errorHandler} from './api/v1/utils/ErrorHandler';
import {BaseError} from './api/v1/utils/BaseError';
import {HttpStatusCode} from './api/v1/constants/HttpStatusCode';
import rTracer from 'cls-rtracer';
export const stream = {
write: (text: string) => {
logger.info(text.replace(/\n$/, ''));
},
};
const swaggerOptions = {
swaggerDefinition: {
info: {
title: 'Backend',
descriptions: 'Service',
contact: {
name: '',
},
servers: ['http://localhost:8080//api/v1/domain'],
version: '1.0.1',
},
},
apis: ['./api/v1/routes/*.ts'],
};
const swaggerDocs = swaggerJSDoc(swaggerOptions);
export class App {
public app: express.Application;
public port: number;
constructor(controllers: Controller[], port: number) {
this.app = express();
this.port = port;
this.initializeMiddlewares();
this.initializeHealth();
this.initializeControllers(controllers);
this.initializeErrorHandler();
this.initializeSwagger();
}
private initializeMiddlewares() {
this.app.use(rTracer.expressMiddleware());
const requestId = rTracer.id();
console.log(requestId); // giving undefined
this.app.use(bodyParser.json());
this.app.use(cors());
this.app.use(
morgan(
[
'ip: :remote-addr',
':method', ':url', 'HTTP/:http-version', 'status: :status',
':res[content-length]', 'referrer: :referrer',
'userAgent: :user-agent', 'responseTime: :response-time ms',
].join(' | '),
{stream: stream},
),
);
this.app.use(express.json());
this.app.use(helmet());
}
private initializeControllers(controllers: Controller[]) {
controllers.forEach((controller) => {
this.app.use('/', controller.router);
});
}
private initializeErrorHandler() {
this.app.use(async (req: Request, res: Response, next: NextFunction) => {
const error = new BaseError('Not Found', HttpStatusCode.NOT_FOUND, true, 'Not Found');
next(error);
});
this.app.use(async (error: Error, req: Request, res: Response, next: NextFunction) => {
if (!errorHandler.isTrustedError(error)) {
// #ts-ignore: Unreachable code error
res.status(error.status).json(error);
}
await errorHandler.handleError(error);
// #ts-ignore: Unreachable code error
res.status(error.httpCode || HttpStatusCode.INTERNAL_SERVER).json({error: error});
});
}
private initializeSwagger() {
this.app.use(
'/api-docs',
swaggerui.serve,
swaggerui.setup(swaggerDocs, {explorer: true}),
);
}
private initializeHealth() { }
public listen() {
this.app.listen(this.port, () => {
logger.info(`listening on the port ${this.port}`);
});
}
}
export default App;
Why does it work flawlessly in the code below:
import express from 'express';
import {CONFIG} from './config';
import MasterRouter from './routers/MasterRouter';
import ErrorHandler from './utils/ErrorHandler';
import rTracer from 'cls-rtracer';
import morgan from 'morgan';
class Server {
public app = express();
public router = MasterRouter;
constructor(
) {
this.correlationalIdMiddleware();
this.loggingMiddleware();
this.routingMiddleware();
this.errorHandlingMiddleWare();
}
correlationalIdMiddleware() {
this.app.use(rTracer.expressMiddleware());
}
loggingMiddleware() {
this.app.use(morgan((tokens, req, res) => {
const requestId = rTracer.id();
return [
`> requestId: ${requestId} -`,
tokens.method(req, res),
tokens.url(req, res),
tokens.status(req, res),
tokens.res(req, res, 'content-length'), '-',
tokens['response-time'](req, res), 'ms',
].join(' ');
}));
}
routingMiddleware() {
this.app.use('/api', this.router);
}
errorHandlingMiddleWare() {
this.app.use((req, res, next) => {
const error = new ErrorHandler(404, 'Not Found');
next(error);
});
this.app.use((error: ErrorHandler, req: any, res: any, next: any) => {
const errorObject = {
status: 'error',
statusCode: error.statusCode,
message: error.message,
};
const requestId = rTracer.id();
console.log(`> requestId: ${requestId} - ${JSON.stringify(errorObject)}`);
res.status(error.statusCode || 500).json(errorObject);
});
}
}
const server = new Server;
server.app.listen(CONFIG.PORT, () => {
console.log(`> Server listening on ${CONFIG.PORT}`);
});

I am using socketio with react as the frontend and node with express js to make an app

When I am trying to connect using socketio client in the front end to the backened it is showin the error Access to XMLHttpRequest at 'http://localhost:8080/socket.io/?EIO=4&transport=polling&t=NOk7Aq9' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
front end code
import React, { Component, Fragment } from "react";
import openSocket from "socket.io-client";
import Post from "../../components/Feed/Post/Post";
import Button from "../../components/Button/Button";
import FeedEdit from "../../components/Feed/FeedEdit/FeedEdit";
import Input from "../../components/Form/Input/Input";
import Paginator from "../../components/Paginator/Paginator";
import Loader from "../../components/Loader/Loader";
import ErrorHandler from "../../components/ErrorHandler/ErrorHandler";
import "./Feed.css";
class Feed extends Component {
state = {
isEditing: false,
posts: [],
totalPosts: 0,
editPost: null,
status: "",
postPage: 1,
postsLoading: true,
editLoading: false,
};
componentDidMount() {
fetch("http://localhost:8080/feed/status", {
headers: {
Authorization: "Bearer " + this.props.token,
},
})
.then((res) => {
if (res.status !== 200) {
throw new Error("Failed to fetch user status.");
}
return res.json();
})
.then((resData) => {
console.log("status fetched ", resData.status);
this.setState({ status: resData.status });
})
.catch(this.catchError);
this.loadPosts();
console.log("openSocket", openSocket);
const socket = openSocket("http://localhost:8080/", {
transports: ["polling", "websocket"],
transportOptions: {
polling: {
extraHeaders: { "Access-Control-Allow-Origin": "*" },
},
},
});
socket.emit("connection", { data: "data" });
socket.on("posts", (data) => {
if (data.action === "create") {
this.addPost(data.post);
}
});
}
backend code
mongoose
.connect(
"mongodb://chitesh:pass123#cluster0-shard-00-00.ulx1q.mongodb.net:27017,cluster0-shard-00-01.ulx1q.mongodb.net:27017,cluster0-shard-00-02.ulx1q.mongodb.net:27017/feed?ssl=true&replicaSet=atlas-demxn2-shard-0&authSource=admin&retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true }
)
.then((result) => {
const server = app.listen(8080); // this basically return us the server
const io = require("./socket.js").init(server);
// websockets uses http protocols the basis
//so we are passing our http based server to the function
// to create a websocket connection
// we are setting up a function
// to be executed whener a new connection is made
io.on("connection", (socket) => {
console.log("Client connected");
});
})
.catch((error) => {
console.log(error);
});
socket.js
const { listenerCount } = require("./models/post");
let io;
module.exports = {
init: (httpServer) => {
io = require("socket.io")(httpServer);
return io;
},
getIO: () => {
if (!io) {
let error = new Error("Socket.io is not initialized");
throw error;
}`enter code here`
return io;
},
};
Take a look at express CORS middleware.
You'll need to allow localhost:3000 to be used as origin.
You can use something like
var express = require('express')
var cors = require('cors')
var app = express()
var corsOptions = {
origin: 'http://localhost:3000',
}
app.use(cors(corsOptions))

Unexepected token U in JSON at position 0

I have a problem with MEAN Stack.
I have an Angular Form with good values to creat a company id DB with Node Express in backend. I have an error that the JSON in Node is Undefined. but i don't understand why ?
app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const userboRoutes = require('./routes/userbo');
const companyRoutes = require('./routes/company');
const path = require('path');
mongoose.connect('mongodb://127.0.0.1/aya', {useNewUrlParser: true})
.then(() => {
console.log('Successfully connected to MongoDB AYA!');
})
.catch((error) => {
console.log('Unable to connect to MongoDB! AYA');
console.error(error);
});
const app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
app.use(bodyParser.json());
app.use('/api/company', companyRoutes);
app.use('/api/authbo', userboRoutes);
module.exports = app;
routes\company.js
const express = require('express');
const router = express.Router();
const companyCtrl = require('../controllers/company');
const Company = require('../models/company');
router.post('/', companyCtrl.createCompany);
router.get('/:id', companyCtrl.getOneCompany);
router.put('/:id', companyCtrl.modifyCompany);
router.delete('/:id', companyCtrl.deleteCompany);
router.get('/', companyCtrl.getAllCompany);
module.exports = router;
controller\company.js
const Company = require('../models/company');
const fs = require('fs');
exports.createCompany = (req, res, next) => {
req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.company.coid,
coname: req.body.company.coname,
service: req.body.company.service,
address: req.body.company.address,
state: req.body.company.state,
zip: req.body.company.zip,
city: req.body.company.city,
country: req.body.company.country,
size: req.body.company.size,
domain: req.body.company.domain,
duns: req.body.company.duns,
tid1: req.body.company.tid1,
numid1: req.body.company.numid1,
tid2: req.body.company.tid2,
numid2: req.body.company.numid2,
tid3: req.body.company.tid3,
numid3: req.body.company.numid3,
bankname: req.body.company.bankname,
bicswift: req.body.company.bicswift,
iban: req.body.company.iban,
datecreat: req.body.company.datecreat,
bogid: req.body.company.bogid
});
company.save().then(
() => {
res.status(201).json({
message: 'Post saved successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
};
Angular Component :
this.companyService.CreateCoData(company).then(
() => {
this.CreateCoForm.reset();
this.router.navigate(['home']);
},
(error)=> {
this.loading = false;
this.errorMessage = error.message;
}
);
Company service
import { Router } from '#angular/router';
import { Company } from './../models/company.model';
import { HttpClient, HttpClientModule } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs';
export class CompanyService {
constructor(private router: Router,
private http: HttpClient) { }
company: Company[];
companySubject = new Subject<Company[]>();
public company$ = new Subject<Company[]>();
CreateCoData(company: Company) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost:3000/api/company', company).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}
I got this error :
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at exports.createCompany (E:\MEAN\BACKEND\controllers\company.js:7:29)
Or in the Request payload (Chrome dev tools network) the json is correct.
I don't understand why the req json in undefined ?
Please help me to understand :)
UPDATE
Just work with POSTMAN :
and update the company.js like this
exports.createCompany = (req, res, next) => {
console.log( req.body);
// req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.coid,
coname: req.body.coname,
service: req.body.service,
address: req.body.address,
state: req.body.state,
zip: req.body.zip,
city: req.body.city,
country: req.body.country,
size: req.body.size,
domain: req.body.domain,
duns: req.body.duns,
tid1: req.body.tid1,
numid1: req.body.numid1,
tid2: req.body.tid2,
numid2: req.body.numid2,
tid3: req.body.tid3,
numid3: req.body.numid3,
bankname: req.body.bankname,
bicswift: req.body.bicswift,
iban: req.body.iban,
datecreat: req.body.datecreat,
bogid: req.body.bogid
});
company.save().then(
() => {
res.status(201).json({
message: 'Post saved successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
};
I think the problem come from a bad data format. But How to set it correctly ?
The .save function returns a callback and not a promise.
So if you modify your request handler as follows it will work:
const Company = require('../models/company');
const fs = require('fs');
exports.createCompany = (req, res, next) => {
req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.company.coid,
coname: req.body.company.coname,
service: req.body.company.service,
address: req.body.company.address,
state: req.body.company.state,
zip: req.body.company.zip,
city: req.body.company.city,
country: req.body.company.country,
size: req.body.company.size,
domain: req.body.company.domain,
duns: req.body.company.duns,
tid1: req.body.company.tid1,
numid1: req.body.company.numid1,
tid2: req.body.company.tid2,
numid2: req.body.company.numid2,
tid3: req.body.company.tid3,
numid3: req.body.company.numid3,
bankname: req.body.company.bankname,
bicswift: req.body.company.bicswift,
iban: req.body.company.iban,
datecreat: req.body.company.datecreat,
bogid: req.body.company.bogid
});
company.save(function (err, newCompany) {
if (err) {
return res.status(400).json({ error: error });
}
return res.status(201).json(newCompany);
});
};
So I Found the SOLUTION ^^ So proud ** ((^o^)/)**
After the update in the first post, I see that the problem is Content-type Error.
So in ** company service** (Angular) I add this to Force JSON Type !
import { HttpClient, HttpClientModule,** HttpHeaders** } from '#angular/common/http';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
CreateCoData(company: Company) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost:3000/api/company', company, **this.httpOptions**).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}

Unable to attach an res.send(result) in my Nodejs to send data to angular app

I have made a Nodejs and angular2 app where i need to integrate them to Neo4j app. I am able to hit the Database from my NodeJS code coming from Angular2 but then i am unable to send that data back to angular2 app. If i give
res.send(result)
anywhere in my function tmsServer , i get error -->
inside catch = Error: Can't set headers after they are sent.
Please help. I want to send my data back to angular app.
tmservercontroller.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", "Virtuallib1"));
// //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();
var request = require('request');
var finalResult ;
router.post('/', tmsServer);
module.exports = router;
function tmsServer(req, res) {
session
.run('MATCH (n) RETURN n LIMIT 5')
.then(function (result){
result.records.forEach(function(record){
console.log("record = ", record);
console.log("result = ", result)
console.log("1]
record._fields[0].properties=",record._fields[0].properties);
res.send(result);
});
})
.catch(function(err){
console.log("inside catch = "+err);
})
res.send('It Works');
session.close();
}
neo4j-primary.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();
}
emptyObj1;
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+ "emptyobj1 = "+ this.emptyObj1);
var url = config.url;
var port = config.port;
var object = {
"emptyObj" : this.emptyObj
}
this.http.post("http://" + url+":" + port +
"/viewNodesStart",this.emptyObj1)
.map(Response => Response)
.subscribe((res: Response) => {
console.log("XXXXXXXXXXXX Response on /viewNodesStart", res);
this.info = res;
if (this.info.statusCode == 200) {
console.log("Data added successfully");
} else {
console.log("Data is not inserted")
}
});
}
}
You can send the response back ONLY once, you have an asynchronous operation running while you send the response "It works" and again sending the response with actual data.
res.send sets response headers to object which should ideally happen once during the request lifecycle.
function tmsServer(req, res) {
session
.run('MATCH (n) RETURN n LIMIT 5')
.then(function (result){
result.records.forEach(function(record){
// This will execute only when the promise is resolved and data is returned from database.
res.send(result); // (RES02)
});
})
.catch(function(err){
console.log("inside catch = "+err);
})
res.send('It Works'); // (RES01) <--- This runs before RES02
session.close();
}
The solution to your answer is to remove RES01.

Browser Fetch() API Is Not Posting Body To Backend Node Server

Client Side Browser:
API
class API {
constructor() {
this.api = "http://localhost:3000";
}
async authenticate(product_id) {
const url = this.api + '/api/auth';
const body = {
"product_id": product_id,
}
console.log(body);
const request = {
method: 'POST',
body: body,
}
return await fetch(url, request);
}
}
module.exports = API;
INDEX
const account = await this.API.authenticate("56729b6b77c82288f746c0cf");
console.log(account)
In my console i get
Response {type: "cors", url: "http://localhost:3000/api/auth",
redirected: false, status: 401, ok: false, …} body : (...) bodyUsed :
false headers : Headers {} ok : false redirected : false status : 401
statusText : "Unauthorized" type : "cors" url :
"http://localhost:3000/api/auth"
Fetch failed loading: POST "http://localhost:3000/api/auth".
Server Side:
app.ts
import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import passport from 'passport';
import cors from "cors";
import Routes from './routes';
import Config from './config/config';
class App {
public app: express.Application;
public config: any;
constructor() {
this.app = express();
this.environment();
this.database();
this.middleware();
this.routes();
}
private environment(): void {
this.config = new Config();
}
private database(): void {
const uri: string = this.config.db.uri;
const options: any = this.config.db.options;
mongoose.connect(uri, options).then(
() => {
console.log("MongoDB Successfully Connected On: " + this.config.db.uri)
},
(err: any) => {
console.error("MongoDB Error:", err);
console.log('%s MongoDB connection error. Please make sure MongoDB is running.');
process.exit();
}
);
}
private middleware(): void {
this.app.use(cors());
this.app.use(logger('dev'));
this.app.use(express.json());
this.app.use(express.urlencoded());
this.app.use(passport.initialize());
}
private routes(): void {
const routes = new Routes(this.app);
}
}
export default App;
api/auth Route
public store(req, res) {
console.log(req.body)
}
the req.body is empty.
You should try adding in the request mode: cors in your request. The body should be a string and you might want to set header with content-type to application/json:
let headers = new Headers();
headers.set('Content-type', 'application/json');
const request = {
method: 'POST',
body: JSON.stringify(body),
mode: 'cors',
credentials: 'include',
headers: headers
}
It would also be helpful to see what happens in your browser network tab.

Resources