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.