0

I want to send a x-www-form-urlencoded request for the server. I give a json value for it like {username: 'asd', password: '12345'}.

Angular:

...
        let headers: HttpHeaders = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
        this._http.post('/api/authentication', form.value, {headers: headers, observe: 'response'}).subscribe((response:HttpResponse<Object>) => {
          console.log(response); // response body {'{"username":"asd","password":"12345"}' : ""}
        });
...

So I get something strange from back-end and I don't really understand what to change in my implementation to make this work like the input he got.

Nodejs (express):

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

--

//api/.../authentication.js
...
router.post('/', (req, res) => {
    let post  = req.body;

    console.log( req.body); //same strange hash: {'{"username":"asd","password":"12345"}' : ""}

    res.status(201).json(req.body);
});
...
Bálint Réthy
  • 411
  • 1
  • 6
  • 25
  • If you use JSON with `Content-Type` as `application/x-www-form-urlencoded`, it'll no longer be JSON. [Check this](https://stackoverflow.com/questions/9870523/differences-in-application-json-and-application-x-www-form-urlencoded) – lifetimeLearner007 Jun 27 '18 at 10:02

1 Answers1

0

Http header application/x-www-form-urlencoded means sending a x-www-form-urlencoded request to the server, that's correct.

However, bodyParser.json only parse request type application/json(default value).

Returns middleware that only parses json and only looks at requests where the Content-Type header matches the type option. Type defaults to application/json.

So it is not correct.

You should send application/json request. Or you should parse it as application/x-www-form-urlencoded, then decode the content (json).

chris
  • 2,761
  • 17
  • 24
  • Could you help me how to "parse it as application/x-www-form-urlencoded, then decode the content (json)" only in this post request? Sorry I am not expert but I want to use application/json by default. On the other hand I want to send login, registration and some other forms with application/x-www-form-urlencoded. – Bálint Réthy Jun 27 '18 at 10:21
  • @BálintRéthy Try use `app.use(bodyParser.json({ type: 'application/x-www-form-urlencoded' }))` – chris Jun 27 '18 at 10:25
  • This request works this case but my others not with application/json :/ – Bálint Réthy Jun 27 '18 at 10:30
  • @BálintRéthy Try to understand and study what I wrote. Also vote and accept. ;P – chris Jun 27 '18 at 10:37