Home > Blockchain >  JavaScript web server receive PUT requests
JavaScript web server receive PUT requests

Time:06-21

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

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

CodePudding user response:

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

  • Related