1
votes

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.

console

1
@Randy No because the request works fine in postmanKay
@Randy I have updated my question to show you the code for my server side app. You can see there i have set cors and bodyParser.Kay
I have even updated to use express.json and urlencoder instead of bodyparser, but this still does not fix the issue.Kay

1 Answers

2
votes

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.