The post request works in Postman and in cURL but not in Angular

Tags: , , , ,



I have a remote server and a local client which sends a simple post request with one header Content-Type: application/json and with the body '{"text": "hello"}'.

The server code is here. It prints the request body and the header.

import * as express from 'express';
import * as bodyParser from "body-parser";

const app = express();
const router = express.Router();

router.route("/home")
    .all(bodyParser.json())
    .all(function (req, res, next) {
        console.log(req.body, req.headers['content-type']); // !!! print to console body and header
        next(); 
    })
    .post( (req, res, next) => {
        res.status(200).json({
                    message: req.body,
                })
            }
    );

app.use((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, PATCH, PUT, POST, DELETE, OPTIONS");
    next();
});
app.use('/api/v1', router);

app.listen(3000, function(){
    console.log('listening on 3000');
});

The post request works fine from Postman and from curl.

curl --location --request POST 'http://vm-gudiea.sio.lab.emc.com:3000/api/v1/home' --header 'Content-Type: application/json' --data-raw '{"text": "hello"}'

For both requests the server prints the following body and content-type header.

{ text: 'hello' } 'application/json'

But I need to send the request from my Angular app. I have the following method in a service there

sendInitialRequest(): void {
    const myHeaders = new HttpHeaders().set('Content-Type', 'application/json');
    this.http.post(this.remoteUrl, JSON.stringify({text: 'hello'}), {headers: myHeaders})
      .subscribe(data => console.log(data));
  }

But if I call the method remote server will print the output

{} undefined

So it didn’t get a Content-Type header and body for some reason. Where is the bug here? How can I send a post request with body and header from an Angular app ?

Answer

if it is related to cors, install this package in you API https://www.npmjs.com/package/cors

then use it as following

import * as cors from 'cors';

...

app.options('*', cors());
app.use(cors());

other tipps:

do not stringify your JSON in the angular request. also there is not need to explicitly set the json header, angular will take care of that for you.

this.http.post(this.remoteUrl, {text: 'hello'})
      .subscribe(data => console.log(data));



Source: stackoverflow