Search code examples
javascriptandroidrestpostloopbackjs

Send formData POST request with string parameter


I have Loopback API and I want to send POST request. This is required from API:

enter image description here

In android, I do it this way:

public static Api getRetrofit(String token) {

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

httpClient.addInterceptor(chain -> {

    Request original = chain.request();
    Request.Builder builder = original.newBuilder()
           .addHeader("x-access-token", token)
           .method(original.method(),original.body());
    return  chain.proceed(builder.build());

});



 String token = mEtToken.getText().toString();
 String password = mEtPassword.getText().toString();
 User user = new User();
    user.setNewPassword(password);
    resetPasswordFinishProgress(user);

And it works.

Now, on website in HTML form, I have a javascript function, in which where I send request, I get a response message from the API with code 400 saying:

{"error":{"statusCode":400,"name":"Error","message":"newPassword is a required argument","stack":"Error: newPassword is a required argument\n

This is function:

function post() {

    const urlParams = new URLSearchParams(window.location.search);
    const token = urlParams.get('access_token');
    console.log("TOKEN:", token);
    const user = {
        newPassword: document.querySelector('#input-password-check').value,
    }

    const http = new XMLHttpRequest()
    http.open('POST', 'https://www.example.com/Users/reset-password')
    http.setRequestHeader('x-access-token', token)
    http.send(JSON.stringify(user))
    console.log(JSON.stringify(user))
    http.onload = function() {
        alert(http.responseText)
    }
}

Log prints this:

{"newPassword":"mypass"}

What am I doing wrong? It looks the same to me as its in android.

If it helps, this is CURL call from the Loopback API:

curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' -d 'newPassword=s' 'https://www.example.com:3000/Users/reset-password?access_token=qRBj0mQYB8MHz6p8MHz68MHz6RBj0mQYB8MHz6RBj0mQYB8MHz6

Solution

  • I found the problem myself.

    I had only authorization header set, and the server side did not get that I am sending json content, I had to add one more header Content-Type:

    const http = new XMLHttpRequest()
        http.open('POST', 'https://www.example.com/Users/reset-password')
        http.setRequestHeader('x-access-token', token)
        http.setRequestHeader('Content-Type', 'application/json')
        http.send(JSON.stringify(user))
        console.log(JSON.stringify(user))
        http.onload = function() {
            alert(http.responseText)
        }