The post request is successful in Postman and cURL, however, it faces issues when executed in Angular

A remote server and a local client are set up to communicate through a simple post request. The client sends the request with one header Content-Type: application/json and includes the body

'{"text": "hello"}'
.

Below is the server code, which displays the request body and 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 has been successfully tested using Postman and 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\"}'

Both requests return the expected body and content-type header.

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

However, when attempting to send the same request from an Angular app, there seems to be an issue:

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

Calling this method results in the following output from the remote server:

{} undefined

It appears that the server did not receive the Content-Type header and body for some reason. What could be causing this issue? How can I ensure successful transmission of post requests with both body and header from an Angular app?

Answer №1

When dealing with CORS issues, make sure to add the 'cors' package to your API. You can find the package here

After installing the package, use it as shown below:

import * as cors from 'cors';

...

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

Additional tips:

Avoid stringifying JSON in angular requests. There's no need to set the json header explicitly, angular will handle that for you.

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

Answer №2

Encountering a cross-origin error? Consider the following solution:

npm install --save cors
import express from 'express';
import cors from 'cors';

const app = express();

app.use(cors());
/* Add your usual routes below */

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create a function library that works seamlessly across all of my Vue.js components?

I am currently in the process of developing a financial application using Vue.js and Vuetify. As part of my project, I have created several component files such as Dashboard.vue Cashflow.vue NetWorth.vue stores.js <- Vue Vuex Throughout my development ...

Failure occurred when attempting to link and display on the page container

I have created a simple app using jQuery Mobile. At some point in the app, I include the following code: <a href="test_es.html" data-role="button">Start!</a> This code snippet loads a new HTML file that contains several jQuery Mobile page ...

Receive a response in fragments from express on the browser

As I work on creating a progress bar to track long-running server-side tasks that may take up to a few minutes, I am exploring different methods to display the progress of each task. While WebSockets and interval polling are options, I prefer using long-po ...

New data received in Akka-Http was processed by converting it to a JSON object

Currently, I am working on completing a POST request by unmarshalling received JSON. I need to update the JSON data before submitting it to a Scala method. val route = (path("createDataSets") & post) { entity(as[DataSetEntity]) { dataSetEntity: Da ...

Having trouble showing a leaflet map on Node.js Express with Jade

As a newcomer to this technology, I'm currently following a tutorial here. My goal is to generate a map view using jade (although I understand it's now called pug). Within my index.js file, I have set up a router request for the map page. This r ...

Avoid changing the button color to a lighter shade when it is clicked

Is there a way to prevent button text from changing to a lighter color after clicking? I am facing an issue where the button I set to red turns slightly whiteish after it is clicked. How can I ensure that the button stays red at all times? Header Toolbar ...

Having trouble launching simple ionic template: Issue with locating module 'fast-deep-equal'

Recently I started using Ionic and followed the steps to install the basic blank template as shown below. First, I installed Ionic and Cordova by running the command: npm install -g ionic Cordova. After that, I created my first Ionic project using the f ...

Integrating Json data from a service in Angular without the use of a data model: A step-by

I received a Nested JSON from my service through a GET call { "id": "7979d0c78074638bbdf739ffdf285c7e1c74a691", "seatbid": [{ "bid": [{ "id": "C1X1486125445685", "impid": "12345", "price": 0, ...

Is it considered secure to make updates to Firestore records directly from the client side?

I've been diving into Firestore and noticed that many libraries are geared towards the client side. Although I'm intrigued by the idea of working on the client side, it seems prone to manipulation. When I authenticate as user A, it appears that ...

Validation needed for data list option

Here are all the details <form action="order.php" method="post" name="myForm" onsubmit="return(validate());"> <input type="text" list="From" name="From" autocomplete="off" placeholder="From Place"> <datalist id="From"> <option valu ...

You can install the precise version of a package as mentioned in package.json using npm

At this moment, executing the command npm install will download the latest versions of packages. Is there a way to install the exact versions specified in the package.json file? ...

A fresh PHP page escapes from the confines of an iframe and expands to occupy the entire

When calling a new url from inside an iframe, the goal is for the new url to break free from the confines of the iframe and appear full screen. The challenge lies in not having control over the call to the new php file, as it is initiated by a credit card ...

What is the best method for iterating through an array and generating a glossary list organized by categories?

I have an array filled with definitions. How can I use Vue.js to iterate through this array and create a glossary list organized by letters? Desired Output: A Aterm: A definition of aterm B Bterm: A definition of bterm C Cterm: A definition of cterm ...

Height of the div dynamically increases upwards

Just a quick question - is there a way to make position: fixed divs at the bottom of an element (such as the body) grow upwards as content is dynamically added? Maybe something like anchor: bottom or increase: up? I'm thinking that using JavaScript m ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

Update and remove data using JavaScript in a Spine.js application

I am in the process of building a small API using Node.js (Express) for my Spine.js application. So far, I have successfully implemented functionality to retrieve and create new objects in the database. However, I have encountered an issue when it comes to ...

Function exported as default in Typescript

My current version of TypeScript is 1.6.2 and we compile it to ECMA 5. I am a beginner in TypeScript, so please bear with me. These are the imported library typings. The contents of redux-thunk.d.ts: declare module "redux-thunk" { import { Middle ...

Install a package using npm while specifying a custom local installation directory

Struggling with installing a local library within another local library and encountering an issue with the package.json: "dependencies": { "@company/lib_name": "file:../../../dist/libs/company/lib_name", ... } Unfortunate ...

Is there a way to modify AJAX response HTML and seamlessly proceed with replacement using jQuery?

I am working on an AJAX function that retrieves new HTML content and updates the form data in response.html. However, there is a specific attribute that needs to be modified before the replacement can occur. Despite my best efforts, I have been struggling ...

Tips for utilizing an array within React and transforming it into a component

I've developed a website that pulls data from a SQL database I created, containing details such as name, address, and occupation of individuals. I successfully managed to showcase this information on the webpage by structuring an array and inserting t ...