0

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?

4
  • Also, it seems like your req.body does not contain any "task", "type" or "subject". You could console.log JSON.stringify(req.body) to see what's inside of the actual object (and not get "[object Object]" Commented Mar 30, 2021 at 21:53
  • It shows that body contains: {} Commented Mar 30, 2021 at 22:01
  • My initial intuitive guess would be that you can't send an array as the top level 'container' of a post request. Try just sending the one object and see what happens. Commented Mar 30, 2021 at 22:44
  • Cody, I've just tried it, but still has undefined on post request from Express. Commented Mar 30, 2021 at 22:55

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

6 Comments

I've just tried it, but still doesn't work
Are you using body-parser module before post middleware? const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({ extended: true }));
andellapie, no I'm not. But I've just tried to use it and it still doesn't work
I've updated my answer with httpOptions. Give it a try
andellapie, I've just updated my program and my post above, but still can only get undefined. I think that I've got a problem with my front end post request. Because at express even when I used JSON.parse(req.body) - it showed "{}"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.