0

I making a post request from my angular application to a node server. I'm using FormData and HttpClient to send the post.

const sendData = new FormData();
sendData.append('aff', loginName);

this.http.post(this.loginURL, sendData, { responseType: 'json' }).subscribe(data => {
  console.log(data);
});

Here is my server side code:

var bodyParser = require('body-parser');

let socketIO = require('socket.io');
var server = http.createServer(app);
let io = socketIO(server);
const port = process.env.PORT || 3002;

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());


app.post('/login', function (req, res) {
    console.log(req.body);
    res.status(200).send({ result: "OK" });
});

server.listen(port, () => {
    console.log(`started on port: ${port}`);
});

When I console log the req.body I get {}. Here is a picture of the network:

enter image description here

I've tried a lot of different things. I'm not sure why this isn't working. I have it working on other websites. Please help!

UPDATE: this works for me.. but still curious as to why FormData isn't working properly...

const sendData = {'username': loginName};
const config = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
this.http.post(this.loginURL, sendData, config).subscribe(data => {
  console.log(data);
});
JD333
  • 501
  • 8
  • 22
  • Are you sure the problem is not url? Change the login to a get, and then try to open this.loginUrl from a web browser if that works then the url is ok and the problem is some where else – cutiko Sep 14 '19 at 23:35
  • Not sure how it could be the url if I get a response in my node server. The console.log(req.body) shows empty brackets {}. So I'm definitely hitting the server. – JD333 Sep 14 '19 at 23:41
  • I think it has something to do with using formdata.. – JD333 Sep 14 '19 at 23:56
  • @JD333 are you using the appropriate body parser for multipart/form-data? I’m not seeing that in the server... – Ramtin Soltani Sep 15 '19 at 01:00
  • @JD333 Try this: https://stackoverflow.com/questions/37630419/how-to-handle-formdata-from-express-4 – Ramtin Soltani Sep 15 '19 at 01:05
  • Yeah that worked. Thank you.. I wasn't able to find that through doing a bunch of google searches. – JD333 Sep 15 '19 at 02:06

0 Answers0