dqwh26750
2018-04-17 15: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."}}

图片转代码服务由CSDN问答提供 功能建议

我需要创建一个登录系统,我尝试将params发送到PHP服务器。 \ n

Angular app

 返回this.http.post&lt; any&gt;('/ s / login / index.php',{
 username:username,  
密码:密码
})。map(user =&gt; {
 console.log(username); 
 //如果响应中有jwt令牌,则登录成功
 if(user){
 /  /将用户详细信息和jwt令牌存储在本地存储中,以保持用户在页面刷新之间登录
} 
 
返回用户; 
}); 
} 
   
 
  

PHP服务器

  if($ _ SERVER [“REQUEST_METHOD”] ==“POST”){
 
 //检查用户名是否为空
if(空)  (trim($ _ POST [“username”]))){
 $ username_err ='请输入用户名。'; 
 $ resp-&gt; body-&gt; message = $ username_err; 
 $ resp = json_encode($  resp); 
 echo $ resp; 
} 
   
 
 

但是服务器总是返回

  {status:“400”,body:{message:“请输入用户名。”}} 
    
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dongyikong6207 2018-04-17 15: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 !

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题