React + Laravel 5.8.33 + Axios:向axios.post请求注册用户时出错;澄清代码问题

Con*_*ack 12 php registration cors laravel reactjs

更新资料

在firefox的开发工具中检查“网络”选项卡,结果如下:

Response headers (290 B)    
Raw headers
Access-Control-Allow-Origin 
*
Allow   
POST
Cache-Control   
no-cache, private
Connection  
close
Content-Type    
text/html; charset=UTF-8
Date    
Sat, 31 Aug 2019 09:45:04 GMT
Date    
Sat, 31 Aug 2019 09:45:04 GMT
Host    
localhost:8000
X-Powered-By    
PHP/7.2.19-0ubuntu0.18.04.2
Request headers (438 B) 
Raw headers
* Accept: */* *
Accept-Encoding 
gzip, deflate
Accept-Language 
en-US,en;q=0.5
Access-Control-Request-Headers  
x-csrf-token,x-requested-with,x-xsrf-token
Access-Control-Request-Method   
POST
Connection  
keep-alive
Host    
localhost:8000
Origin  
http://127.0.0.1:8000
Referer 
http://127.0.0.1:8000/register
User-Agent  
Mozilla/5.0 (X11; Ubuntu; Linu…) Gecko/20100101 Firefox/68.0
Run Code Online (Sandbox Code Playgroud)

为什么使用GET方法?尝试从工具中更改它,它表明不允许使用POST方法。另外,在提交请求时,它提供以下信息:

更新资料

我开始对需要我的axios的bootstrap.js文件进行更改,但是没有成功。我尝试改变

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Run Code Online (Sandbox Code Playgroud)

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
};
Run Code Online (Sandbox Code Playgroud)

但实际上,我不能说清楚一点。我无法理解评论中的链接教程是如何工作的,并且我开始对所要看的内容缺乏任何想法。因此,感谢您的帮助;如果有人可以指向一个有效的引用说,看,这是一个未解决的问题,那么我将使用其他代码来实现py项目;但是,如果不是这样,我这个问题就应该解决。如果这是我的一个小错误,那么它到底在哪里?谢谢大家。

注意:在我的原始帖子中,我没有显示我的网络路线。由于我是从Laravel内部使用React(我在终端php artisan预设react;中使用了),因此我的网络路由来自预先配置的laravel代码

Route::get('/', function () {
    return view('welcome');
});
Run Code Online (Sandbox Code Playgroud)

到调用React应用程序的新代码:

Route::view('/{path?}', 'app');
Run Code Online (Sandbox Code Playgroud)

Update3:我试图(从昨天开始)更改我的apache2 conf,但问题仍然存在。我不知道这是否可以作为更改:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/user/register. (Reason: missing token ‘x-requested-with’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/user/register. (Reason: CORS request did not succeed).

Source map error: request failed with status 404
Resource URL: http://127.0.0.1:8002/js/app.js
Source Map URL: popper.js.map
Run Code Online (Sandbox Code Playgroud)

Update2:我尝试更改axios发布请求:

const dataofuser={
    name:data.name,
    email:data.email,
    password:data.password
}


 const instance = axios.create({
     method:'post',
     baseURL: 'http://localhost:8000/api/user/',
     timeout: 1000,
     headers: {'Access-Control-Allow-Origin': '*' , 'Access-Control-Allow-Methods ':  'POST, GET, OPTIONS, PUT, DELETE','Access-Control-Allow-Headers':  'Content-Type, X-Auth-Token, Origin, Authorization','X-Requested-With': 'XMLHttpRequest' }
 });

instance          .post("register/create",dataofuser)
           .then(response => {
            console.log(response);
            return response;
          })
           .then(json => {
            if (json.data.success) {
              alert(`Registration Successful!`);
              history.push('/')
Run Code Online (Sandbox Code Playgroud)

...但是,我得到了

无效的标题名称


原始 正如我在另一篇文章前面提到的,目前我自学反应,Laravel。我正在尝试使用React作为前端和Laravel作为后端构建一个基本的注册应用程序。这篇文章是关于我填写注册表并尝试提交时出现的错误;用户没有注册,并且根据我的尝试我会遇到一些错误。

如果我尝试:

axios
          .post("http://localhost:8000/api/user/register", {
              name: data.name,
              email: data.email,
              password: data.password
          })
Run Code Online (Sandbox Code Playgroud)

我进入控制台:

> Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/user/register. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/user/register. (Reason: CORS request did not succeed).

>Source map error: request failed with status 404
Resource URL: http://127.0.0.1:8000/js/app.js
Source Map URL: popper.js.map

>[object Object] Error: Network Error 
Run Code Online (Sandbox Code Playgroud)

如果我尝试

axios
  .post("/user/register", {
      name: data.name,
      email: data.email,
      password: data.password
  })
Run Code Online (Sandbox Code Playgroud)

然后我得到(我相信这是关于错误的路线定义的错误):

Source map error: request failed with status 404
Resource URL: http://127.0.0.1:8000/js/app.js
Source Map URL: popper.js.map
Run Code Online (Sandbox Code Playgroud)

如果我用

axios
  .post("/api/user/register", {
      name: data.name,
      email: data.email,
      password: data.password
  })
Run Code Online (Sandbox Code Playgroud)

我得到:

Source map error: request failed with status 404
Resource URL: http://127.0.0.1:8000/js/app.js
Source Map URL: popper.js.map

[object Object] Error: Request failed with status code 500
Run Code Online (Sandbox Code Playgroud)

我不确定(我无法澄清)是否存在CORS问题(尽管我已采取措施来防止此类问题)或其他一些路由,数据传递或语法问题。我会去解决CORS问题(尽管我完全不知道popper.js.map通知是关于什么的)。我在下面发布代码。


更新1

我只是在Chrome浏览器中使用

 axios
          .post("http://localhost:8000/api/user/register", {
              name: data.name,
              email: data.email,
              password: data.password
          })
Run Code Online (Sandbox Code Playgroud)

我得到了

Access to XMLHttpRequest at 'http://localhost:8000/api/user/register' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
app.js:70270 [object Object] Error: Network Error
app.js:371 POST http://localhost:8000/api/user/register net::ERR_FAILED
Run Code Online (Sandbox Code Playgroud)

看来我有一个CORS问题...而且我从昨天和今天整天都无法理解如何处理它。


一些代码:

我的App(父)组件包含一个传递给Register(子)组件的函数;此功能处理注册过程

        import React, {Component} from 'react'
        import ReactDOM from 'react-dom'
        import {BrowserRouter, Route, Switch } from 'react-router-dom'
        // import {Link} from 'react-router-dom'
        import Header from './Header'
        import Intro from './Intro'
        import Register from './Register'
        import Login from './Login'
        import Userpage from './Userpage'
        import Footer from './Footer'
        import Science from './Science'
        import Literature from './Literature'
        // import {AppState} from 'react-native'


        class App extends Component {

            constructor(props){
                super(props);
                this.state={
                    isLoggedIn:false,
                    user:{},
                    data_user:'',
                    data_username:''
                }

                this.username_Callback=this.username_Callback.bind(this)
                this._registerUser=this._registerUser.bind(this)



            }

            componentDidMount() {
                let state = localStorage["appState"];
                if (state) {
                  let AppState = JSON.parse(state);
                  console.log(AppState);
                  this.setState({ isLoggedIn: AppState.isLoggedIn, user: AppState });
                }
          }

            _registerUser(data){

                $("#email-login-btn")
                  .attr("disabled", "disabled")
                  .html(
                    '<i class="fa fa-spinner fa-spin fa-1x fa-fw"></i><span class="sr-only">Loading...</span>'
                  );



                // var formData = new FormData(); 
                // formData.append('data.name');
                // formData.append('data.email');
                // formData.append('data.password');

                console.log(data)
                console.log(data.name)
                console.log(data.email)
                console.log(data.password)
                // console.log(formData)



                axios
                  .post("http://localhost:8000/api/user/register", {
                      name: data.name,
                      email: data.email,
                      password: data.password
                  })
                  .then(response => {
                    console.log(response);
                    return response;
                  })
                  .then(json => {
                    if (json.data.success) {
                      alert(`Registration Successful!`);
                      history.push('/')


                      let userData = {
                        name: json.data.data.name,
                        id: json.data.data.id,
                        email: json.data.data.email,
                        auth_token: json.data.data.auth_token,
                        timestamp: new Date().toString()
                      };
                      let appState = {
                        isLoggedIn: true,
                        user: userData
                      };
                      // save app state with user date in local storage
                      localStorage["appState"] = JSON.stringify(appState);
                      this.setState({
                        isLoggedIn: appState.isLoggedIn,
                        user: appState.user
                      });
                    } else {
                      alert(`Registration Failed!`);
                      $("#email-login-btn")
                        .removeAttr("disabled")
                        .html("Register");
                    }
                  })
                  .catch(error => {
                    alert("An Error Occured!" + error);
                    console.log(`${data} ${error}`);
                    $("#email-login-btn")
                      .removeAttr("disabled")
                      .html("Register");
                  });

          };



render(){
                return(


                    <BrowserRouter>

                        <Header listNameFromParent={this.state.data_username} />

                        <Footer />

                        <Switch>
                            <Route exact path='/' component={Intro} />
                            <Route path='/register' render={props=><Register {...props} registerUser={this._registerUser}/>}/>

                            <Route path='/login' render={props=><Login {...props} loginUser={this._loginUser}/>}/>
                            <Route path='/userpage' component={Userpage}/>
                            <Route path='/science' component={Science}/>
                            <Route path='/literature' component={Literature}/>

                        </Switch>


                    </BrowserRouter>




                    )
            }
        }

        ReactDOM.render(<App />, document.getElementById('app'))
Run Code Online (Sandbox Code Playgroud)

我的注册组件仅包含表单并返回输入数据。使用console.log命令,我正在验证数据确实在我的App中和我的注册函数中可用。如果询问,我可以发布代码。

在我的后端,我有:

api.php

<?php

        use Illuminate\Http\Request;

        // header('Access-Control-Allow-Origin: *');
        // //Access-Control-Allow-Origin: *
        // header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
        // header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization');
        /*
        |--------------------------------------------------------------------------
        | API Routes
        |--------------------------------------------------------------------------
        |
        | Here is where you can register API routes for your application. These
        | routes are loaded by the RouteServiceProvider within a group which
        | is assigned the "api" middleware group. Enjoy building your API!
        |
        */

        Route::middleware('auth:api')->get('/user', function (Request $request) {
            return $request->user();
        });


        Route::group(['middleware' => ['jwt.auth','api-header']], function () {

            // all routes to protected resources are registered here  
            Route::get('users/list', function(){
                $users = App\User::all();

                $response = ['success'=>true, 'data'=>$users];
                return response()->json($response, 201);
            });
        });
        Route::group(['middleware' => 'api-header'], function () {

            // The registration and login requests doesn't come with tokens 
            // as users at that point have not been authenticated yet
            // Therefore the jwtMiddleware will be exclusive of them
            Route::post('/user/login', 'UserController@login');
            Route::post('/user/register', 'UserController@register');
        });
Run Code Online (Sandbox Code Playgroud)

API.php(中间件)

<?php

        namespace App\Http\Middleware;

        use Closure;

        class API
        {
            /**
             * Handle an incoming request.
             *
             * @param  \Illuminate\Http\Request  $request
             * @param  \Closure  $next
             * @return mixed
             */
            public function handle($request, Closure $next)
            {
                $response = $next($request);
                $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token');
                $response->header('Access-Control-Allow-Origin','*');
                $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
                $response->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With');
                $response->header('Access-Control-Allow-Credentials',' true');
                //add more headers here
                return $response;
            }
        }
Run Code Online (Sandbox Code Playgroud)

UserController

<?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\User;
    use JWTAuth;
    use JWTAuthException;


    class UserController extends Controller
    {
        private function getToken($email, $password)
        {
            $token = null;
            //$credentials = $request->only('email', 'password');
            try {
                if (!$token = JWTAuth::attempt( ['email'=>$email, 'password'=>$password])) {
                    return response()->json([
                        'response' => 'error',
                        'message' => 'Password or email is invalid',
                        'token'=>$token
                    ]);
                }
            } catch (JWTAuthException $e) {
                return response()->json([
                    'response' => 'error',
                    'message' => 'Token creation failed',
                ]);
            }
            return $token;
        }
public function register(Request $request)
        { 


            $validator = Validator::make($request->all(), [
                'name' => 'required|max:255',
                'email' => 'required',
                'password' => 'required'
            ]);
            if ($validator->fails()) {
                return response()->json(['errors'=>$validator->errors()],422);
            }





            $payload = [
                'password'=>\Hash::make($request->password),
                'email'=>$request->email,
                'name'=>$request->name,
                'auth_token'=> ''
            ];




            $user = new \App\User($payload);
            if ($user->save())
            {

                $token = self::getToken($request->email, $request->password); // generate user token

                if (!is_string($token))  return response()->json(['success'=>false,'data'=>'Token generation failed'], 201);

                $user = \App\User::where('email', $request->email)->get()->first();

                $user->auth_token = $token; // update user token

                $user->save();

                $response = ['success'=>true, 'data'=>['name'=>$user->name,'id'=>$user->id,'email'=>$request->email,'auth_token'=>$token]];        
            }
            else
                $response = ['success'=>false, 'data'=>'Couldnt register user'];


            return response()->json($response, 201);
        }
    }
Run Code Online (Sandbox Code Playgroud)

再次重申,我无法确切说明问题所在,并且注册程序无效。

Clu*_*tor 6

如果您使用rest API,则需要注意CORS。

CORS本质上是一种浏览器安全功能,而不是服务器端。

默认情况下,浏览器将不允许某些跨源请求。您正在与之交谈的服务器可以发布使用跨源请求是否安全,但是了解并使用该信息的是客户端,因此提供了保护而不是服务器。

浏览器通过OPTIONS方法自动在原始请求之前发送HTTP请求,以检查发送原始请求是否安全。

只需通过尝试使用laravel-corslaravel-cors软件包在服务器端启用CORS,软件包即可使用Laravel中间件配置发送跨源资源共享标头。

或以其他方式,您可以在laravel标头中添加以下行。

'Access-Control-Allow-Methods': 'POST, GET, PUT, OPTIONS, DELETE'
'Access-Control-Allow-Origin': '*'
'Access-Control-Allow-Credentials': ' true'
Run Code Online (Sandbox Code Playgroud)


Olu*_*ule 4

预检请求是HTTP-OPTIONS客户端向服务器发出的请求,以验证服务器是否支持 CORS 协议。

https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

解决方法是在服务器中注册一个路由,该路由返回带有必要的访问控制策略标头的响应。例如:

Route::options('/{path}', function() {
  return response('', 200)
      ->header(
        'Access-Control-Allow-Headers', 
        'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token, X-Requested-With')
      ->header('Access-Control-Allow-Methods', 'POST, GET, PUT, OPTIONS, DELETE')
      ->header('Access-Control-Allow-Origin','*')
      ->header('Access-Control-Allow-Credentials',' true');
})->where('path', '.*');

Run Code Online (Sandbox Code Playgroud)

这与您问题中的中间件方法类似,只是中间件附加到路由,但不为对options这些路由的请求提供后备。