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

Paypal Payment Plans on a Monthly Basis Utilizing the Bootstrap Pricing Slider

I came across this fantastic Bootstrap Pricing Slider that I found originally at Within my Bootstrap Pricing Slider, there is a "total amount" calculated after some math, resulting in a final score. The slider includes a "Process" button which currently ...

Waiting for a method to finish in Node.js/Javascript

Currently, I am in the process of creating a trade bot for Steam. However, I have encountered an issue where the for-loop does not wait for the method inside it to finish before moving on to the next iteration. As a result, the code is not functioning as i ...

On what occasion is a DOM element considered "prepared"?

Here's a question that might make you think twice: $(document).ready(function() { }); Sometimes, the simplest questions lead to interesting discussions. Imagine having a list of elements like this: <body> <p>Paragraph</p> < ...

Sending data using jQuery when a button is clicked

Is there a way to display the text from a text box when a button is clicked? Here's what I have been attempting: <script type="text/javascript> $(function() { $('#button').click(function(){ $.ajax({ type: "PO ...

When I upload a file using v-file-input, it displays two names

While working with nuxt, I made an interesting discovery. See the pattern here The top name is the file that was uploaded, and the bottom one is the target file name. I plan to remove the bottom name and replace it with the top. This is what I envision: E ...

Using React.js to create a modal that includes ExpansionPanelDetails with a Checkbox feature

I am trying to achieve a specific visual effect with my code. Here is an example of the effect I want: https://i.stack.imgur.com/cJIxS.png However, the result I currently get looks like this: https://i.stack.imgur.com/547ND.png In the image provided, y ...

Customize Link Appearance Depending on Current Section

Looking for a way to dynamically change the color of navigation links based on which section of the page a user is currently viewing? Here's an example setup: <div id="topNav"> <ul> <li><a href="#contact">Contac ...

Issue verifying the initial certificate in Nodeshift

Currently, I am in the process of deploying an Angular application using nodeshift, but I have encountered the error message "unable to verify the first certificate" whenever I execute the following command: nodeshift --strictSSL=false --dockerImage=buch ...

Setting up roles and permissions for the admin user in Strapi v4 during the bootstrap process

This project is built using Typescript. To streamline the development process, all data needs to be bootstrapped in advance so that new team members working on the project do not have to manually insert data into the strapi admin panel. While inserting ne ...

What could be causing the updated JavaScript file to not run on a live Azure website using ASP.NET MVC?

After making a minor adjustment to my JavaScript file on my deployed ASP MVC website hosted on Azure, I decided to redeploy everything. However, upon checking the resource files, I noticed that the JavaScript had indeed been changed, but the behavior of th ...

Guide to: Implementing Radio Buttons to Adjust Image Opacity

How can I dynamically change the opacity of an image using JavaScript when a radio button is clicked? I attempted to achieve this using a forEach function, but the current code causes all images to instantly switch to opacity 1; Additionally, after refre ...

Displaying text files containing escaped characters using Express.js

I am facing an issue with my JSON object that has a text file within one of its fields. When I have Express render this text as "text/plain" in the response, it does not respect the '\n' line breaks and instead prints everything on one line. ...

Unable to retrieve values from input fields that have been established using interpolation

I'm currently developing a straightforward app that involves a form with formArray. Within the formArray, users can select a product name and amount. Once both are chosen, a third input field - total - computes the total price of the items (product pr ...

Unexpected error encountered with node.js when attempting to run: npm run dev. A TypeError was thrown stating that require(...) is not

Working on my initial project, I have set up a database and am in the process of creating a login page. However, when trying to run it using 'npm run dev', an error is encountered (see below). I am unsure of what is causing this issue and how to ...

Sort an array of objects by matching string properties with elements from another array

If the array of objects is represented by rows and wantedBrands consists of an array of strings, how can I achieve a specific result? let rows = [ { name: "Russia", brands: ['XM1', 'XM2', 'XM3'] }, ...

"Exploring the features of next-auth server-side implementation in the latest version of Next.js,

Is it possible to utilize next-auth in a Next.js 14 application router to access user sessions and display page responses using SSR? If so, what steps need to be taken? ...

What is the functionality of the cookie-session middleware in Express.js?

Could someone explain the underlying concepts of cookie-session in expressjs to me? When we store something in session, like this: req.session.myName = "Manas Tunga"; Where is this session data actually stored? Is it in client-side session cookies or in ...

When a timeout is triggered, the AngularJS Promise is not being cancelled

In my endeavor to incorporate a simple timeout feature into my promise, I set out with the intention that if I do not receive a response within 1 second, the request should be terminated. The code should not hang for a response nor execute any code intende ...

Error encountered: Application module "MyApp" not found

I have set up AngularJs and jQuery using RequireJs within a nodeJs framework. This is my main.js setup require.config({ paths: { angular: 'vendor/angular.min', bootstrap: 'vendor/twitter/bootstrap', jqu ...

showing javascript strings on separate lines

I need assistance with displaying an array value in a frontend Angular application. How can I insert spaces between strings and show them on two separate lines? x: any = [] x[{info: "test" + ',' + "tested"}] // Instead of showing test , teste ...