dqwh26750 2018-04-17 07:07
浏览 68
已采纳

this.http.post不会发送角度为4的参数

I need to create a login system, I try to send the params to the PHP server.

Angular app

return this.http.post<any>('/s/login/index.php', {
                username: username,
                password: password
            }).map(user => {
                console.log(username); 
                // login successful if there's a jwt token in the response
                if (user) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                }

                return user;
            });
    }

PHP server

if($_SERVER["REQUEST_METHOD"] == "POST"){

 // Check if username is empty
if(empty(trim($_POST["username"]))){
    $username_err = 'Please enter username.';
    $resp->body->message=$username_err;
    $resp=json_encode($resp);
    echo $resp;
}

But the server always returns

{status: "400", body: {message: "Please enter username."}}
  • 写回答

1条回答 默认 最新

  • dongyikong6207 2018-04-17 07:16
    关注

    It is because you are not setting headers.

    first import necessary modules

    import {HttpClient,HttpHeaders} from '@angular/common/http';
    import {URLSearchParams} from '@angular/http';
    

    try it this way.

    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    let options = {
        headers: headers
    };
    
    let body = new URLSearchParams();
    body.set('username', username);
    body.set('password', password);
    
    return this.http.post<any>('/s/login/index.php', body, options).map(user => {
                console.log(username); 
                // login successful if there's a jwt token in the response
                if (user) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                }
    
                return user;
            });
    }
    

    Tell me if it does not work. I am here !

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部