Search code examples
httppostpolymerput

How does HTTP POST work in Polymer?


I want to know how POST calls work in Polymer. I know that I have to use POST calls for sending sensitive information such as user passwords and access tokens. I tried doing this :

<iron-ajax
        id="AjaxPost"
        url="/api/login"
        method="POST"
        content-type="application/x-www-form-urlencoded"
        handle-as="json"
        on-response="_handleAjaxPostResponse"
        on-error="_handleAjaxPostError"
        ></iron-ajax>


this.$.AjaxPost.params = { email: "abc@gmail.com", password: "password" };
this.$.AjaxPost.generateRequest();

But, this will set the parameters in the URL, which can be viewed in the browser console like :

POST http://localhost:8080/api/login?email=abc%40mgail.com&password=password 400 (Bad Request)

The PUT method allows you to set the data in body, which I think is more secure. Now I have 2 questions :

  1. Can we set the body of POST method too? Or setting params is same as setting body?
  2. If that is possible, how should I extract the data in the server side?

PS: We are not using SSL HTTPS connection. Having said that, which method can be incorporated for better security?


Solution

  • The api document for iron-ajax defines body attribute as below:

    body
    Object default:
    Body content to send with the request, typically used with "POST" requests.
    If body is a string it will be sent unmodified.
    If Content-Type is set to a value listed below, then the body will be encoded accordingly.

    content-type="application/json"
        body is encoded like {"foo":"bar baz","x":1}
    content-type="application/x-www-form-urlencoded"
        body is encoded like foo=bar+baz&x=1
    

    Otherwise the body will be passed to the browser unmodified, and it will handle any encoding (e.g. for FormData, Blob, ArrayBuffer).

    To send the data as body, you should modify your request as below

    <iron-ajax
            id="AjaxPost"
            url="/api/login"
            method="POST"
            content-type="application/json"
            handle-as="json"
            on-response="_handleAjaxPostResponse"
            on-error="_handleAjaxPostError"
            ></iron-ajax>
    
    
    this.$.AjaxPost.body = { "email": "abc@gmail.com", "password": "password" };
    this.$.AjaxPost.generateRequest();