Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 19

8
votes
answers
34 views
+10

React+Laravel 5.8.33 +Axios: errors when registering user with an axios.post request; clarififying the code problem

Update

Checking my network tab in my dev-tools of firefox gives me this:

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

Why is the method GET? Trying to change it from the tools, it gives that POST method isn't allowed. Also, when submitting the request, it gives the following info:

Update

I started making changes to bootstrap.js file, where my axios is required, but I had no success. I tried changing

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

to

window.axios = require('axios');

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

but really, I can't get to a point. I cannot understand how the linked tutorial in my comments worked and I am starting to have a shortage of ideas on what to look. So, any help is appreciated; if someone can point to a valid reference that says, look, this is an unsolved problem, then I will implement py project with a different code; but if not, I this problem shouldn't remain unsolved. If it's a minor mistake from my part, then where exactly is it? Thanks to all.

Note: On my original posts, I didn't showed what my web routes look like. Since I am using React from inside Laravel(I used in terminal php artisan preset react ;) my web routes went from the pre-configured laravel code

Route::get('/', function () {
    return view('welcome');
});

to the new code that calls the React app:

Route::view('/{path?}', 'app');

Update3: I have tried(from yesterday) to change my apache2 conf and my problem remains. I don't know if this is to be taken as change though:

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

Update2: I tried changing my axios post request:

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('/')

... But, then I get

invalid header name


Original As I have mentioned before in another post, I am currently self study React and Laravel. I am trying to build a basic registration app with React as front-end and Laravel as back-end. This post is about errors coming when I fill out the registration form and try to submit it; the user doesn't gets registered and I get several errors depending on what I am trying.

If I try:

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

I get in console :

> 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 

If I try

axios
  .post("/user/register", {
      name: data.name,
      email: data.email,
      password: data.password
  })

then I get(I believe this an error regarding bad route definition ):

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

If I use

axios
  .post("/api/user/register", {
      name: data.name,
      email: data.email,
      password: data.password
  })

I get:

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

I am not sure anymore(I cannot clarify) if I have a CORS problem (although I have taken actions that should prevent such issues) or some other, routing or data-passing or just syntactic issue. I would go for the CORS problem(altough I have no idea what that popper.js.map notification is all about). I am posting the code below.


Update1:

I just ran my code in Chrome browser with the

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

and I got the

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

It seems I have a CORS problem... and I cant understand from yesterday and all day today how to handle it.


Some code:

My App(parent) component contains a function that gets passed to a Register(child) component; this function handles the registration process

        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'))

My Register component just contains the form and returns the input data. Using a console.log command, I am verifying that the data are indeed available in my App and inside my register function. If asked, I can post the code.

At my back-end I have:

api.php

<?php

        use IlluminateHttpRequest;

        // 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 = AppUser::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');
        });

API.php(middleware)

<?php

        namespace AppHttpMiddleware;

        use Closure;

        class API
        {
            /**
             * Handle an incoming request.
             *
             * @param  IlluminateHttpRequest  $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;
            }
        }

UserController

<?php

    namespace AppHttpControllers;

    use IlluminateHttpRequest;
    use AppUser;
    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 AppUser($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 = AppUser::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);
        }
    }

So again, I cannot clarify what the issue is exactly and the registration procedure doesn't work.

沙发
+50

如果您正在使用rest API,那么您需要处理CORS。

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

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

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

只需在服务器端启用CORS即可尝试 laravel-cors 或<

谢谢你的回答。在laravel标题中你是什么意思?正如帖子一样,我已将它们添加到我的中间件中。你的意思是别的什么?谢谢。 - 康斯坦丁布莱克8月31日8:19

我认为这应该是有效的。因为我主要使用前端技术并连接在php,node,ASP.NET core 2中创建的API。因此,我们需要仅从后端启用CORS。您是否能够从邮递员或任何其他工具测试API调用? - Clue Mediator 8月31日13:53

是。我今天打算尝试一下。当laravel为应用程序提供服务时,我是否有机会从php artisan服务的方式获得此问题?或者从我如何从laravel里面调用我的反应前端(我已经使用了php artisan预设反应 - 如果你对此有所了解的话)。谢谢。 - 君士坦丁黑8月31日15:24

我会说首先用postman检查你的简单GET API。如果它的工作,那么尝试在反应中集成相同的API。如果您在响应中收到CORS错误,那么仅在服务器端进行更改(因为只有服务器端更改可以解决您的问题),为此您必须通过在API中间件中添加三行来启用CORS。 - Clue Mediator 8月31日17:19

CORS基本上是一个浏览器安全功能,而不是服务器端。默认情况下,浏览器不允许某些跨源请求。您正在与之交谈的服务器可以发布使用跨源请求是否安全,但是客户端了解并使用该信息,因此提供的保护不是服务器。浏览器通过OPTIONS方法自动在原始HTTP请求之前发送HTTP请求,以检查发送原始请求是否安全。 - Clue Mediator 2天前

板凳
+30

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

https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request < p>要做的就是在服务器中注册一个路由,该路由返回带有必要访问控制策略头的响应。例如:

  Route :: options('/ {path}',function(){return response('',200) - &gt;标题('Access-Control-Allow-Headers','Origin,Content-Type,Content-Range,Content-Disposition,内容描述,X-Auth-Token,X-Requested-With') - &gt;标题('Access-Control-Allow-Methods','POST,GET,PUT,OPTIONS,DELETE') - &gt;标题(' Access-Control-Allow-Origin','*') - &gt; header('Access-Control-Allow-Credentials','true'); }) - &gt; where('path','。*');   

这与您的问题中的中间件方法类似,只是中间件附加到路由,但没有为这些路由提供 options 请求的回退。 header('Access-Control-Allow-Credentials','true'); }) - &gt; where('path','。*');

这与您的问题中的中间件方法类似,只是中间件附加到路由,但没有为这些路由提供 options 请求的回退。 header('Access-Control-Allow-Credentials','true'); }) - &gt; where('path','。*');

这与您的问题中的中间件方法类似,只是中间件附加到路由,但没有为这些路由提供 options 请求的回退。

谢谢你的回答。你的意思是我应该用它代替我的api.php文件中的其他路径或者用它们? - 君士坦丁黑8月30日17:23

两种方式,它似乎都不起作用。 - 君士坦丁黑8月30日17:26

在预检响应中返回的Access-Control-Allow-Headers必须包含请求中使用的所有标头。您的问题中的错误消息显示缺少X-Requested-With标头。 - Oluwafemi Sule 8月30日19:10

我同意。但应该在哪里进行更正?在中间件,apache2服务器,api或web路由,在内核的某个地方,在axios,在laravel的csrf标记的调用?谢谢。 - 君士坦丁黑8月31日8:22

这应该在Laravel中考虑你的问题中的Update 3。 - Oluwafemi Sule 8月31日9:11

地板
0

我将在这里发布我如何弄清楚我的Laravel-React-Axios简单注册应用程序发生了什么。从上述试图解决问题的帖子中,只有ClueMediator的一些评论对如何理解幕后问题以及Quentin在我的帖子中提供的一些信息性有用的评论有所帮助。我必须在这里注意,据我所知,关于axios和laravel以及.js前端的所有其他帖子和github讨论根本没有关注这个(或者如果他们这样做,他们没有放任何认真的关注)。

首先,我可以在我的第一篇文章中看到将post请求从localhost:8000更改为api / route的名称似乎具有效果删除一些人; 因为我一次在一个或两个服务器上运行项目,作为工匠为应用程序提供服务的地方,cors可能会回来。

其次,即使是减少了角色的情况,也会出现内部500错误; 这是由于我正在学习的教程中的错误,并且与迁移的不完整构造有关。

重点。似乎axios总是试图发送,连同我在我的代码中的请求(在这个例子中是一个post请求)一个选项请求。我做的是检查问题是在工匠正在服务时更改我的主机和端口,并将我的代码放在一起以正确匹配路由。然后,检查控制台上的网络选项卡,我看到虽然post请求发送正常,但我仍然有cors因为axios.options请求默认发送到localhost:8000,但< / em>我没有从那里提供我的应用程序。指定工匠从那里服务,并纠正迁移建设,解决了这个问题。

在这里强调一些东西很重要:artisan在localhost:8000第一次打开他/但打开第二台服务器时服务,它会像通常那样继续下一个可用的端口。如果没有迁移代码中的错误,我可能会发现问题来自工匠和服务的地方。但是,'导致与我的数据库关系失灵的原因,即便如此,我得到500错误,因为内部服务器错误,让我打开另一台服务器,然后发现axios总是只向localhost:8000发送选项请求,甚至如果我的前端和后端彼此达成一致,对代码进行了很多更改产生了不一致。因此,总而言之,在处理坏代码(我应该比我更快看到的东西)之后,只需要正确设置axios和artisan达成一致。

关于上述内容的任何观察逻辑可以改善将是伟大的。

感谢所有人。

我还要注意,我不知道这是否是一个更普遍的社区维基,可以收集与laravel-js-axios相关的许多问题。 - Constantine Black 2天前

4楼
0

您是否尝试使用 csrf 标记作为post参数?如果不是你可以做的是,在 axios 请求的post参数中设置 csrf token token 它将解决您的问题。

这个问题已经解决了。ClueMediator的评论有助于更好地理解,我也发布了问题所在的位置。当然这不是csrf问题。不管怎么说,还是要谢谢你。 - 昨天康斯坦丁·布莱克

0
votes
answers
62 views
+10

laravel中的引導模態動態內容ajax

0

我想從ajax的引導模式中加載內容我可以在警報或控制檯日誌中獲取它,但是我想更新的部分消失了!我嘗試了$('。modal-content')。html(數據),但是我的模態內容消失或者.append(數據),但它不起作用!laravel中的引導模態動態內容ajax

我重拍了它真的很簡單,但它仍然沒有工作,即時通訊我錯誤的?

感謝您的時間和幫助!

部分關閉我的主頁

<a class="btn btn-primary" class="quickview22" href="#" data-target="#quickviewMain55" data-categorie="1" data-trigger="hover" data-toggle="modal">Trigger modal</a> 
@include('bootmodal') 

我bootmodal觀點

<div class="modal fade in " id="quickviewMain55"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
       <h4 class="modal-title">Modal ffffffffffffffftitle</h4> 
      </div> 
      <div class="modal-body"> 
       <h1>{{ $quickProducts1->first()->name }}</h1> 

      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
       <button type="button" class="btn btn-primary">Save changes</button> 
      </div> 
     </div> 
    </div> 
</div> 

這是我的腳本

jQuery(document).ready(function($) { 
    $('#quickviewMain55').on('show.bs.modal', function(e) { 

    var category = $(e.relatedTarget).data('categorie'); 

    $.ajax({ 

      url: 'quick-view', 
      data: { category : category }, 
      success: function(data) 
      { 


     $('.modal-content').html(data); 


      alert(data); 
      } 
     }); 


}); 
}); 

     $.ajaxSetup({ 
    headers: { 
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
    } 
}); 



</script> 

我控制器

class QuickViewController extends Controller 
{ 
    public function index(Request $request) 
    { 



     $quickProducts1 = Product::where('category_id', $request->category)->get(); 



     return view('bootmodal', compact('quickProducts1'))->render(); 
    } 

} 
沙发
0
0

您確定要將它追加到.modal-content而不是.modal-content .modal-body

你可能也想嘗試: $('.modal-content .modal-body').html(data)

讓我們更新!

肯尼

+0

我個人建議'$(」模式內容.modal體H1' )。追加(數據)' – ProEvilz

0
votes
answers
45 views
+10

如何確定在OSX上偵聽什麼進程

0

試圖幫助在運行El Capitan的Mac上配置Laravel代客,並且用戶以前安裝了MAMPMAMP已被禁用,但無論何時我們加載代客地址(mysite.dev),我們都會收到標準的Apache 404頁面。如何確定在OSX上偵聽什麼進程

有沒有辦法確定什麼進程在端口80上偵聽,並與代客衝突,所以我可以禁用它?

+0

你可以希望適應這一個https://stackoverflow.com/a/24388281/2836621 –

沙发
0
0

Who is listening on a given TCP port on Mac OS X?

lsof -n -i4TCP:80 | grep LISTEN 

或類似。

0
votes
answers
49 views
+10

laravel - 從數據庫中刪除laravel和的updated_at列created_at後試圖插入他們

0

我已刪除created_at和從的updated_at數據庫,但laravel試圖插入這些列,但是我已經都在控制器數據庫和代碼刪除。我認爲有些東西是緩存的。順便說一句,我不希望在模型中使用public $timestamps = false,因爲它似乎他們是多餘的和不必要的。laravel - 從數據庫中刪除laravel和的updated_at列created_at後試圖插入他們

+0

你從遷移中刪除? – Serge

+0

是的!從數據庫中刪除,遷移,控制器! – codepro

沙发
0
0

唉,其實你需要設置:

public $timestamps = false; 

因爲在默認情況下它的假設模型有時間戳(事實上這是非常合理的所有表格中幾乎讓他們)這不是多餘的和不必要的。

時間戳節省記錄過程中使用:

if ($this->usesTimestamps()) { 
    $this->updateTimestamps(); 
} 

所以當您使用雄辯此屬性設置爲false,如果你沒有在表中的那些列沒有其他辦法更短。

+0

所以你的意思是每個表需要這兩列,他們是必需的?我不確定!因爲我有幾張桌子沒有這兩個,並且正常工作! – codepro

+0

如果你使用口才救了所有的表應該由缺省時間戳除了透視表。但是,如果您正在使用查詢生成器,則不需要它們。 –

+0

我不知道數據透視表是什麼。我所知道的是我用過雄辯,他們都不需要它! – codepro

0
votes
answers
47 views
+10

Laravel - Bootstrap 4不能正常工作

0

我爲我的laravel項目使用引導程序4,但由於某種原因,它不能正常工作,我試圖設置一個類似這樣的帖子: 一列爲個人資料圖片col-md-1和11列是col-md-11後的其餘但由於某些原因,它原來是這樣enter image description hereLaravel - Bootstrap 4不能正常工作

取而代之的是:enter image description here

這怎麼可能?我有同樣的問題與另一頁,我的設置是這樣的

<div class="container first-container"> 
    <div class="row" id="showEffect"> 
     <div class="col-md-9 col-sm-12" style="border-right: 1px solid #f1f0f0"> 
      <h2 class="fw-3">Alle vragen</h2><br> 
      <div class="row"> 
       @foreach($posts as $post) 
        <div class="card" style="border: 0; border-bottom: 1px solid #f1f0f0"> 
         <div class="card-body"> 
          <div class="col-md-1 col-sm-1"> 
           <a href=""> 
            <img src="{!! asset('images/placeholder.png') !!}" class="rounded-circle" width="50"> 
           </a> 
          </div> 
          <div class="col-md-11 col-sm-11"> 
           <a href="{{ $post->path() }}"> 
            <h5 class="mb-0">{{ $post->title }}</h5> 
           </a> 
           <small> 
            <span>Kanaal</span> • {{ $post->created_at->diffForHumans() }} door 
            <a href=""> 
             <span>{{ $post->user->username }}</span> 
            </a> 
           </small> 
           <p class="mb-0 mt-2">{{ $post->text }}</p> 
          </div> 
         </div> 
        </div> 
       @endforeach 
      </div> 
     </div> 
     <div class="col-md-3"> 
      test 
     </div> 

    </div> 


</div> 

出於某種原因,最後col-md-3在BUTTOM應該在網頁的BUTTOM旁邊col-md-9而是它的顯示。我的引導程序4的實現是非常有用的,我可以注意到按鈕的顏色。但是,怎麼注意這個?提前致謝!

PS:這裏是元素的GIF https://imgur.com/a/2FP67

沙发
0
0

很難說究竟是怎麼回事,沒有看到,可能是替代CSS規則,但嘗試添加「行」類的父「COL-MD-1」 和 「col-MD-11」:

<div class="row card-body"> 
    <div class="col-md-1 col-sm-1"> 
     ... 
    </div> 
    <div class="col-md-11 col-sm-11"> 
     ... 
    </div> 
</div> 

見文檔here

0
votes
answers
41 views
+10

laravel 5.4驗證自定義規則陣列

0

我在驗證需要自定義規則的字段數組時遇到問題。我有以下驗證:laravel 5.4驗證自定義規則陣列

$validator = Validator::make($request->all(), [ 
    'order'  => 'required', 
    'service_id.*' => Rule::unique('order_services')->where('order_id', $request->order), 
    'due_date.*' => 'required|date', 
    'vendor' => 'required|integer', 
    'instructions' => 'string|nullable', 
    'lock_box' => 'string|nullable', 
    ]); 

到期日排列驗證就好了,但服務ID返回以下錯誤:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'service_id.0' in 'where clause' (SQL: select count(*) as aggregate from `order_services` where `service_id`.`0` = 10 and `order_id` = 100f) 

服務ID規則防止重複記錄有相同的順序號,服務ID

規則在驗證單個服務ID時按預期工作,我只是不確定如何同時驗證多個服務ID。

在此先感謝

沙发
0
0

默認情況下,Laravel使用鍵unique作用,因爲它是一個數組,鍵是0,1,2,依此類推。該解決方案是獨特的規則將列名這樣的:

Rule::unique('order_services', 'id')->where('order_id', $request->order), 

顯然,在你的情況,你可能需要其他的列名比id(這取決於你的應用程序)

+0

謝謝!我結束了使用Rule :: unique('order_services','service_id') - > where('order_id',$ request-> order), – Wireland

0
votes
answers
88 views
+10

Vue公司2.X + Laravel 5.4在資源管理器

0

我正在寫在Laravel 5.4和Vue的2 +紗 我得到的IE錯誤以下JS錯誤的一個項目不工作(版本9-11)Vue公司2.X + Laravel 5.4在資源管理器

  1. 語法錯誤(行,其中有在常量和箭頭功能的使用)
  2. 對象不支持屬性或方法「startsWith」

我缺少什麼?我想知道我是否在濫用babel或者其他的東西不見了。我在這裏完全感到沮喪,因爲我已經花了這麼多時間來研究爲什麼在涉及Vue 2組件時IE無法正常工作。任何幫助或建議在這裏將不勝感激!

app.js:

require('./bootstrap'); 

var Promise = require('es6-promise').Promise; 
require('babel-polyfill') 
Promise.polyfill(); 
window.Vue = require('vue'); 
import Vue2Filters from 'vue2-filters' 
import BootstrapVue from 'bootstrap-vue' 

我webpack.mix.js(試圖安裝巴貝爾)

mix.js('resources/assets/js/app.js', 'public/js') 
    .sass('resources/assets/sass/app.scss', 'public/css') 
    .babel('out.es6.js', 'out.js') 
    .options({ 
     polyfills: [ 
      'Promise' 
    ] 
}); 

我的package.json

{ 
    "private": true, 
    "scripts": { 
     "dev": "npm run development", 
     "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", 
     "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", 
     "watch-poll": "npm run watch -- --watch-poll", 
     "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js", 
     "prod": "npm run production", 
     "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", 
     "build": "babel src -d lib" 
    }, 
    "devDependencies": { 
     "accounting": "^0.4.1", 
     "axios": "^0.15.3", 
     "babel-cli": "^6.26.0", 
     "babel-core": "^6.26.0", 
     "babel-loader": "^7.1.2", 
     "babel-polyfill": "^6.26.0", 
     "babel-preset-env": "^1.6.1", 
     "babel-preset-vue-app": "^1.3.1", 
     "bootstrap-sass": "^3.3.7", 
     "cross-env": "^3.2.3", 
     "jquery": "^3.1.1", 
     "laravel-mix": "0.*", 
     "lodash": "^4.17.4", 
     "vue": "^2.4.2", 
     "vue-template-compiler": "^2.4.2", 
     "webpack": "^3.8.1" 
    }, 
    "dependencies": { 
     "bootstrap-vue": "^1.0.0-beta.7", 
     "es6-promise": "^4.1.1", 
     "vee-validate": "^2.0.0-beta.17", 
     "vue-events": "^3.0.1", 
     "vue-strap": "^1.1.37", 
     "vue2-filters": "^0.1.9", 
     "vuelidate": "^0.5.0" 
    } 
} 
+0

我使用IE和AFAIK的Vue應用程序,Vue只需要Promises填充。但是如果您使用箭頭功能,請確保您使用正確的babel設置。我認爲你需要babel-preset-es2015 - 即。 – WaldemarIce

+0

['startsWith'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith)在IE中不可用,您需要對它進行填充。 Transpiling不會自動填充缺少的函數,只爲您翻譯語法。 – apokryfos

沙发
0
0

我成功化解問題通過運行babel代碼,將結果回顯到特定位置:

我的.bashrc:

{ 
    "presets": ["es2015"] 
} 

命令:

./node_modules/.bin/babel public/js/app.js > public/js/out.js 

然後在佈局文件,我包括公共/ JS/out.js文件,而不是公共/ JS/app.js

0
votes
answers
52 views
+10

作曲家安裝--optimize,磁帶自動加載機生產拋出找不到服務提供商

0

我正在開發使用Laravel 5.5作曲家安裝--optimize,磁帶自動加載機生產拋出找不到服務提供商

我在開發環境中做什麼,沒有錯誤的應用:

  1. 運行composer require spatie/laravel-permission
  2. 增加這個服務提供商config/app.php'providers' => [SpatiePermissionPermissionServiceProvider::class,];

如果我有服務Provi之前註冊安裝spatie/laravel許可,然後我想我會得到錯誤「服務提供商」找不到。這就是發生在生產,因爲應用了後,我就部署到生產服務提供商已經註冊,因此運行composer install --optimize-autoloader拋出以下錯誤消息,當部署失敗:

[Symfony\\Component\\Debug\\Exception\\FatalThrowableError]   
Class 'Spatie\\Permission\\PermissionServiceProvider' not found 

如何避免這個錯誤?

沙发
0
0

他們已經在composer中添加了autoload ServiceProvider。你其實並不需要把它添加到您的config/app.php文件

參見:https://github.com/spatie/laravel-permission/blob/master/composer.json

+0

好的,謝謝。還有一件事,如果我使用的Laravel超過5.4,需要將服務提供程序添加到'config/app.php'文件?在部署應用程序時如何解決'未找到服務提供者'問題? – cawecoy

0
votes
answers
45 views
+10

Laravel郵件參數(sendmail/smtp)

0

我想弄清楚如何設置我的郵件參數。Laravel郵件參數(sendmail/smtp)

我有一個域名production.mydomain.be。我創建了一個郵件地址[email protected]。但我的問題是現在,我如何設置我的郵件參數?我選擇了sendmail還是smtp?

Laravel文檔對sendmail/smtp沒有太多的說明。

+0

https://stackoverflow.com/questions/24709988/laravel-smtp-email –

+0

這不是關於Laravel,它是關於你的服務器。你的服務器上是否安裝了郵件服務器(例如Postfix)? –

+0

已安裝Postfix。我應該使用smtp.mydomain.be而不是smtp.gmail.com? – nielsv

沙发
0
1

你應該選擇smtp

您需要填寫usernamepassword字段順序與SMTP服務器登錄,並且還提供與hostport該連接的有效信息。您的服務器管理員應該爲您提供該信息以及加??密。

0
votes
answers
22 views
+10

如何在使用REST API時發送cookie?

0

使用Laravel 5並試圖將一些數據從我的網站發送到另一個,這爲我提供了REST API。但他們使用cookies作爲授權。目前,我已成功通過身份驗證。並堅持如何通過POST方法將此cookie發送到API接口?這是我的列表。如何在使用REST API時發送cookie?

Thanx提前。

P.S.所有的事情都在控制器內進行。

if (Cookie::get('amoauth') !== null) { 
      //COOKIE IS HERE 
      $client = new Client(); 
      $newlead = $client->post('https://domain.amocrm.ru/private/api/v2/json/leads/set', [ 
       'add' => [ 
        'add/name' => 'TEST LEAD', 
        'add/date_create' => time(), 
        'add/last_modified' => time(), 
        'add/status_id' => '1', 
        'add/price' => 5000 
       ] 
      ]); 
     } else { 
      $client = new Client(); 
      $auth = $client->post('https://domain.amocrm.ru/private/api/auth.php',[ 
       'USER_LOGIN' => 'login', 
       'USER_HASH' => 'hash', 
       'type' => 'json' 
      ]); 
      $auth = $auth->getHeaders('Set-Cookie'); 
      Cookie::queue('amoauth', $auth, 15); 
      return redirect('/test'); 
     } 

現在返回我的以下內容:

Client error: `POST https://domain.amocrm.ru/private/api/v2/json/leads/set` resulted in a `401 Unauthorized` response. 
+0

發現這個:https://github.com/guzzle/guzzle/issues/1400但仍然不知道如何實現它(通過此鏈接描述相同的情況)。 – Dmitri

+0

試圖使用'CookieJar:$ jar = new GuzzleHttp Cookie CookieJar(Cookie :: get('amoauth'));'但仍然獲得'401 Unauthorized' ...也許我在獲取和存儲這個來自API提供商的cookie? – Dmitri

+0

這是我從API提供者成功驗證後得到的結果:[link](https://pastebin.com/PECa1xdv)。這是存儲cookie:[鏈接](https://pastebin.com/PDVBiwNh)。任何想法都值得肯定。 – Dmitri

沙发
0
0

找到了解決辦法:切換到ixudra/curl