我正在构建一个依赖于单独的Laravel API的Angular应用程序,并且我正在尝试注册一个新用户。
开箱即用,Laravel 5.1 Authentication提供了许多方便注册用户的方法,但它们适合在整个应用程序中使用Laravel,这意味着blade template
前端。
我将此添加到我的routes.php文件中:
$router->controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
为我提供了路由/auth/register
,因此我尝试创建新用户:
来自DHC:
很抱歉,Chrome API不允许获取响应正文 重定向。
从我的应用程序:
XMLHttpRequest无法加载http://dde.localhost/auth/register。该 请求已重定向到' http://dde.localhost/home',即 不允许需要预检的跨领域请求。
我发现原因是因为/auth/register
中的postRegister()
方法调用了RegistersUsers.php
:
App\Http\Controllers\Auth\AuthController@postRegister
看起来像:
public function postRegister(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::login($this->create($request->all()));
return redirect($this->redirectPath());
}
这有一个重定向,我猜通常会重定向到刀片欢迎模板或其他东西。
如果我注释掉重定向,只需返回200 response
,
return Response::make('user created', 200);
我收到一条CORS错误:
http://dde.localhost/auth/register。 No' Access-Control-Allow-Origin'标头出现在请求的资源上。
这很奇怪,因为我通过BarryCORS中间件路由所有路由:
Route::group(['middleware' => 'cors'], function(\Illuminate\Routing\Router $router) {
允许使用*
来源。
所以问题是:如何为只使用Laravel for API的前端应用设置注册和身份验证
对于来自我的前端应用程序的每个单独调用,似乎有两次调用register
:
首先:好像第一个请求有访问控制标头,它是一个OPTIONS http请求:
Request URL:http://dde.localhost/auth/register
Request Method:OPTIONS
Status Code:200 OK
//Response Headers:
access-control-allow-headers:ACCEPT, CONTENT-TYPE
access-control-allow-methods:GET, POST, PUT, DELETE
access-control-allow-origin:http://localhost:1337
Allow:GET,HEAD,POST,PUT,PATCH,DELETE
第二次:在第二次,最后调用POST,并使用有效负载,但访问控制头被剥离
Request URL:http://dde.localhost/auth/register
Request Method:POST
Status Code:500 Internal Server Error
//Response Headers: there are no access-control-allow methods attached
//Payload
{username: "testname", password: "some random password"}
为什么会这样?
答案 0 :(得分:3)
在CORS呼叫之前的OPTIONS请求是标准的,正是检查服务器的响应头。
如果您收到HTTP 500,那是因为服务器出了问题。如果仅用于CORS,则会出现40x的错误。 检查你的laravel app日志,有些东西正在破坏服务器端。