Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript web server receive PUT requests

I’m trying to get PUT requests from a service in my Angular app, but I can’t get the data from the request’s body because is undefined. Here is my code.

ANGULAR

setSessionName(sessionId: number, newSessionName: string): Observable<Session> {
    const body = {
      sessionId: sessionId,
      newName: newSessionName
    };
    return this.httpClient.put<Session>(`${this.baseUrl}/set-session-name`, body);
  }
}

SERVER

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const express = require('express');
const cors = require('cors');

const serverPort = 8080;

const app = express();
app.use(cors({
  origin: ['http://localhost:4200']
}));

app.put('/set-session-name', (httpRequest, httpResponse) => {
  console.log(httpRequest.body); // Output: undefined
  httpResponse.sendStatus(200);
});

app.listen(serverPort, () => {
  console.log(`Server running at http://127.0.0.1:${serverPort}`);
})

>Solution :

you need to add app.use(express.json()); in order to add support json encoded bodies in your node-server

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading