0

I read many posts about how to send json to express via post but none worked or fixed my issue.

my issue is that when reading req.body where req is the request object i get an output like this : { '{"z":"z"}': '' } for this obejct i sent {z:"z"}

That is not expected and not any kind of behavior is saw before.

this si the angular httpClient request :

return new Promise((res,rej)=>{
        this.http.post("http://localhost:3000/Auth/Login",{z:"z"},{headers:new HttpHeaders('Content-Type:application/x-www-form-urlencoded')})
            .toPromise()
              .then(
              response =>{
               res(response)
              }
              ).catch(
                  err=>{
                      rej(err)
                  }
              )
    })

This is the server code :

router.route('/Login').all(function (req, res, next) {
    next();
}).post(function(req, res, next) {
    console.log(req.body);})

what i want is to get the same object i sent that is it.

Help !

Kaki Master Of Time
  • 1,428
  • 1
  • 21
  • 39

1 Answers1

0

In service (or where you use connection with api) use HttpClient from @angular/common/http - because only in the HttpClient you can use HttpHeaders.

Example with simple service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class AppService {

  constructor(private http: HttpClient) { }

  toparams = function ObjecttoParams(obj) {
    var p = [];
    for (var key in obj) {
      p.push(key + '=' + encodeURIComponent(obj[key]));
    }
    return p.join('&');
  };

  login(): any {
    return new Promise((res, rej) => {
      let obj = { z: "z" };
      this.http.post("http://localhost:3000/Login", this.toparams(obj), {headers:new HttpHeaders('Content-Type:application/x-www-form-urlencoded')})
        .toPromise()
        .then( response => {
            res(response)
          }
        ).catch(err => {
            rej(err)
          }
        )
    })
  };
}

In module:

import { HttpModule } from "@angular/http"
...
imports: [
  ....
  HttpModule
],

Node.js + express example:

var express = require('express');
var app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.all("/*", function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, X-Auth");
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
    return next();
});

app.route('/Login').all(function(req, res, next) {
    next();
}).post(function(req, res, next) {
    console.log(req.body);
    res.json(req.body)
});

app.listen(3000)

Now when you send { z: "z" } api will return the same object he will not parse it to JSON.

Would not it be easier to get JSON?

ambussh
  • 740
  • 1
  • 7
  • 18