当其他应用程序请求时,Laravel API 返回“500 内部服务器错误”

问题描述 投票:0回答:3

使用laravel API进行测试,使用Fiddler或Postman时返回200。

Postman result

但是当我尝试从另一个Web应用程序访问后,请求失败。

My app result

API的登录功能。

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

在另一个网络应用程序上运行:

public function req()
{
    $client = new Client();
    $response = $client->request('post', 'http://testapi/api/login', [
            'form_params' =>
                ['email' => '[email protected]',
                    'password' => '123456']
        ]
    );

    $r = $response->getBody()->getContents();
    return redirect('/home');
}

通过反复试验,我意识到没有生成令牌,我无法理解为什么会发生这种情况,因为在 Postman 和 Fiddler 的帮助下一切正常。

执行到达这条线,一切都会下降。

 $success['token'] = $user->createToken('MyApp')-> accessToken;

请知情人士帮忙!我将非常感激!

php laravel guzzle
3个回答
1
投票

此 Web 应用程序是否在 Laravel 应用程序之外的另一个域上运行?如果是这样,您可能需要研究 CORS(跨源资源共享)支持。 这似乎是一个流行的 CORS 支持包https://github.com/barryvdh/laravel-cors

我希望这对你有帮助。

编辑:

$user->createToken('MyApp')->
accessToken

之间有一个空格

喜欢:

$user->createToken('MyApp')-> accessToken
应该是
$user->createToken('MyApp')->accessToken
。你的代码中解决了吗?

与返回语句中的这一部分相同

$this-> successStatus
应该是
$this->successStatus
。另外,successStatus 定义了吗?

如果这不是问题,请尝试在

dd()
上执行
$user->createToken('MyApp')
并查看是否返回任何内容。如果是,请检查是否存在
accessToken
属性。


0
投票

当您的方法与接收到的方法不相等时,就会发生这种情况。 提交方法应该是像

post
一样的
postman
,这样就不会出现错误。 另外,要以 json 形式显示信息,配方标头本身的值必须是
Accept
应等于
Application/json
.


0
投票

因为它受 csrf 令牌保护,这是您在测试环境时的解决方案。

评论此行

\App\Http\Middleware\VerifyCsrfToken::class,

在app\Http\Kernel.php

© www.soinside.com 2019 - 2024. All rights reserved.