发送带有字符串参数

时间:2019-03-20 11:55:20

标签: javascript android rest post loopbackjs

我有Loopback API,我想发送POST请求。这是API所必需的:

enter image description here

在android中,我是这样操作的:

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);

它有效。

现在,在HTML格式的网站上,我有一个javascript函数,在其中发送请求的地方,我从API收到响应消息,代码为400,说:

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

这是功能:

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)
    }
}

日志显示以下内容:

{"newPassword":"mypass"}

我在做什么错?对我来说,它和android中的一样。

如果有帮助,请通过回送API进行CURL调用:

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

1 个答案:

答案 0 :(得分:0)

我自己发现了问题。

我只设置了授权标头,并且服务器端没有得到我正在发送json内容,我不得不再添加一个标头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)
    }