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();

    .all(function (req, res, next) {
        console.log(req.body, req.headers['content-type']); // !!! print to console body and header
    .post( (req, res, next) => {
                    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");
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 '' --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');, 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 ?


if it is related to cors, install this package in you API

then use it as following

import * as cors from 'cors';


app.options('*', 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., {text: 'hello'})
      .subscribe(data => console.log(data));

Source: stackoverflow