doq13207
doq13207
2016-10-29 16:40

如何将Laravel与AngularJS一起使用?

已采纳

I am trying to use Laravel with AngularJS and want to understand the best way to set up such a project.

Should I (A) have a single domain and consume an API from the Laravel project, or (B) have website.com and api.website.com and consume the API as if it were a 3rd party API?

I can see pros and cons for each, but what I can't get my head around is how routing would work with option A. I assume the initial routing would be via Laravel to display a top level view and then from that point onwards AngularJS would do the routing, but surely AngularJS and its routing are only initialized when the page loads. For example, if a user goes to a subroute without hitting the site root, no route on the Laravel side will exists for that and thus would it not respond with 404/Not Found?

What is the best setup for consuming my Laravel API within AngularJS?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanji1902 duanji1902 5年前

    I suggest to separate (your option b).

    • Front and back-end are totally separated
    • You can replace one of them without problems in the other
    • Use middleware, json responses and http status codes
    • Use a framework for back-end too (for example Laravel or Lumen)

    About routes ...

    Your back-end has its own routes (endpoints).

    Your front-end has its own routes (totally different), but should send GET/POST/PUT etc. requests to the back-end. The back-end returns (json) response, which will be parsed by the front-end.

    Develop both separately! So you can use the back-end for third party later.

    点赞 评论 复制链接分享