1

I'm using this code:

var creds = "username=" + 'user' + "&password=" + 'password';
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
http.post('http://localhost:3000/', creds, {
  headers : headers
})
    .map(res => res.json())
    .subscribe(
        data => this.logData(data),
        err => this.logError(err),
    () => console.log('Quote Complete')
);

NodeJs got json { username: 'user', password: 'password' } on this.request.body . But I need json like {fields: { username: 'user', password: 'password' } }

2 Answers 2

1

If you want to use url encoded form only, you can't. In fact, your Node application will convert / deserialize the string content (username=user&password=somepwd) into a simple (and flat) JavaScripty object.

To achieve what you want (a specific format) for the data you receive in the Node application, you need to switch to a application/json content type for your request payload, as described below:

var creds = {
  fields: {
    username: 'user',
    password: 'password'
  }
}

var headers = new Headers();
headers.append('Content-Type', 'application/json');
http.post('http://localhost:3000/', JSON.stringify(creds), {
  headers : headers
})
  .map(res => res.json())
  .subscribe(
    data => this.logData(data),
    err => this.logError(err),
    () => console.log('Quote Complete')
  );

Don't forget to register the correct deserializer within your Node application. For example with Express:

var express = require('express');
var application = express();

application.use(bodyParser.json());

Hope it helps you, Thierry

Sign up to request clarification or add additional context in comments.

Comments

1

Make the object of the specified format, use json.stringify to make a string out of it and send it to node.js server.

Comments

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.