【问题标题】:Passport/axios not post username passwordPassport/axios 不发布用户名密码
【发布时间】:2020-02-15 16:47:55
【问题描述】:

我正在尝试 POST 用户名,auth 的密码到 Laravel/Passport 但它总是返回 null

axios.post('http://localhost:8000/api/login', {
    withCredentials: true,
    auth: {
      email: 'agent@test.com',
      password: 'qwerty!@#$%^'
    }
  })
  .then(res => {
    console.log(res);
  })

PassportController.php

public function login(){
    if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
        $user = Auth::user();
        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        return response()->json(['success' => $success], $this-> successStatus);
    }
    else{
        return response()->json(['email'=>request('email')], 401);
// I return email to see value
// return response()->json(['error'=>'Unauthorised'], 401);
    }
}

api.php

Route::post('login', 'PassportController@login');

我检查了很多次,感觉一切正常,但由于某种原因,数据没有发送到护照。

控制台日志:

POST http://localhost:8000/api/login 401(未经授权)

{email: null}
email: null

【问题讨论】:

    标签: php laravel axios


    【解决方案1】:

    最后我解决了我的问题,问题是不需要通过axios 发送credentialsauth 因为从后端laravel 接受post 数据而不是auth 数据,所以我通过了emailpassword通过表单数据而不是身份验证:

    axios.post("http://localhost:8000/api/login", {
        email: "agent@test.com",
        password: "qwerty!@#$%^"
      })
      .then(res => {
        console.log(res);
      });
    

    现在我在后端得到了令牌。

    【讨论】:

      【解决方案2】:

      Laravel 可能正在使用 request 访问 POST 数据的值。 axios.post 方法的第二个参数是作为 POST 数据发送的对象,因此您可能只想将电子邮件和密码作为顶级键传递:

      axios
        .post(
          "http://localhost:8000/api/login",
          {
            email: "agent@test.com",
            password: "qwerty!@#$%^"
          },
          { withCredentials: true }
        )
        .then(res => {
          console.log(res);
        });
      

      我怀疑您通常将身份验证与HTTP ("Basic") Authentication 混淆了。 auth 键是 config 对象的一部分,您可以将其作为第三个参数传递给 axios.post,这将控制它。我认为这不是您所追求的,只是为了完整性而将其添加到此处。请注意,基本身份验证接受 用户名 和密码:

      axios
        .post("http://localhost:8000/api/login", {}, {
            withCredentials: true,
            auth: {
                username: "agent@test.com",
                password: "qwerty!@#$%^"
            }
        })
        .then(res => {
          console.log(res);
        });
      

      【讨论】:

      • 第一个代码失败,返回相同,但对于第二个示例,它什么也不返回,在网络选项卡中返回 200 OK 但预览中没有数据,我应该说它在 postman 上运行良好使用POST并将电子邮件密码设置为表单数据并返回令牌。
      • 啊,注意到我在控制台出现错误,CORS 来源
      • 啊,经典。很高兴你找到了它!
      • 所以,我在这里有点困惑,应该在 Laravel 还是 Axios 中使用 CORS?我已经在laravel中有CORS中间件,在axios中也设置了Access-Control-Allow-Origin,还是一样的错误。
      • 感谢您的帮助,我当然会这样做
      猜你喜欢
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 2015-04-29
      • 2014-04-29
      相关资源
      最近更新 更多