GlKosh
GlKosh

Reputation: 87

Problem with sending data from Angular to Express

I'm trying to post data from Angular to Express.js

This is my function connected to the button (TypeScript):

  upload(): void {
    const nameFromId = document.getElementById('taskName') as HTMLInputElement;
    this.taskName = nameFromId.value;

    const testData = [
      {
        task: this.taskName,
        selectedType: this.selectedType,
        selectedSubject: this.selectedSubject
      }
    ];
    const body = JSON.stringify(testData);
    this.http.post('/api/upload', body)
      .subscribe();

"body" is not null

This is express:

const express = require('express');
const path = require('path');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');


app.use(bodyParser.urlencoded({
  extended: true
}));


app.post('/api/upload', (req, res) => {
  let task = req.body.task;
  let selectedType = req.body.selectedType;
  let selectedSubject = req.body.selectedSubject;

  console.log("task: " + task);
  console.log("type: " + selectedType);
  console.log("subject: " + selectedSubject);
  console.log("server: " + req.body);
  res.end("yes");
})

app.use(express.static(__dirname + '/dist/al'));

app.get('/*', function (req, res) {

  res.sendFile(path.join(__dirname + '/dist/al/index.html'));
});

app.listen(process.env.PORT || port);

And this is what I get as a mistake:

mistake from console

If I put extra options to my "post method" from Angular and write something like:

this.http.post('/api/upload', body, {responseType: 'text'})
      .subscribe();

After adding responseType: 'text' this mistake is no longer exists, but when it comes to console.log all data, that I posted to express, undefined:

Express console.log

What am I doing wrong?

Upvotes: 0

Views: 316

Answers (1)

andellapie
andellapie

Reputation: 176

You are sending a string as http request body. Don't use JSON.stringify, try sending object as is.

const testData = [
      {
        task: this.taskName,
        selectedType: this.selectedType,
        selectedSubject: this.selectedSubject
      }
    ];

const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json',
    })
}

this.http.post('/api/upload', testData, httpOptions)
  .subscribe();

Also add this line to server:

app.use(bodyParser.json());

Finally:

const bodyParser = require('body-parser');    
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

Upvotes: 2

Related Questions