Laravel 和 Angular 的跨域来源问题

huangapple go评论71阅读模式
英文:

cors origin problem with laravel and angular

问题

I understand that you want a translation of the code portions without additional information. Here's the translation of the code sections you provided:

以下是要翻译的代码部分:

  1. 第一个控制器代码:
<?php

namespace App\Http\Controllers;

use App\Models\locations;
use Illuminate\Http\Request;

class locationController extends Controller
{
    public function store(Request $request){
        $data = $request->validate([
            'name'=>'required|min:3'
        ]);
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>locations::create($data)
        ];
         return response()->json($response,200)->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
        
    }
       
    public function delete($id){
        $location = locations::destroy($id);
      
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$location
        ];
        return response($response,200)->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');  
    }
    
    public function update(locations $location,Request $request){
        $data = $request->validate([
            'name'=>'required',
        ]);
        $location->update($data);
        $location->save();
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$location
        ];
        return response($response,200)->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');  
    }

    public function getById($id){
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>locations::find($id)
        ];
        return response($response,200);
    }
    
    public function index(){
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>locations::all()
        ];
        return response($response,200);
    }
}
  1. 第二个控制器代码:
namespace App\Http\Controllers;

use App\Models\Lands;
use App\Models\locations;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\QueryBuilder\QueryBuilder;

use function PHPSTORM_META\map;

class landController extends Controller
{
   public function store(Request $request){
    
    $data = $request->validate([
        'ownerName'=>'required',
        'size'=>'required',
        'price'=>'required',
        'phoneNumber'=>'required',
        'locations_id'=>'required',
        'aquariumNumber'=>'required',
        'partNumber'=>'required',
        'streetNumber'=>'required',
        'streetWide'=>'required'
    ]);
    
    $land = Lands::create($data);
    $response = [
        'returnCode'=>200,
        "errorMsg"=>"",
        "result"=>$land
    ];
    return response($response, 200)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
   
   }

    public function index(Request $request){
        $lands = lands::with(['locations'])->get();
      
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$lands
        ];
        return response($response,200);
    }
    
    public function getById($id){
        $lands = lands::with(['locations'])->find($id);
      
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$lands
        ];
        return response($response,200); 
    }
    
    public function handleCorsPreflight()
    {
        return response(null,200)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    }
    
    public function delete($id){
        $lands = lands::destroy($id);
      
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$lands
        ];
        return response($response,200);  
    }
    
    public function update(Lands $land,Request $request){
        $data = $request->validate([
            'ownerName'=>'required',
            'size'=>'required',
            'price'=>'required',
            'phoneNumber'=>'required',
            'locations_id'=>'required',
            'aquariumNumber'=>'required',
            'partNumber'=>'required',
            'streetNumber'=>'required',
            'streetWide'=>'required'
        ]);
        $land->update($data);
        $land->save();
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$land
        ];
        return response($response,200);  
    }
}
  1. 第一个控制器的路由:
Route::get('/location/getall',[locationController::class,'index']);
Route::get('/location/getbyid/{id}',[locationController::class,'getById']);
Route::post('/location/add',[locationController::class,'store']);
Route::put('/location/update/{location}',[locationController::class,'update']);
Route::delete('/location/delete/{id}',[locationController::class,'delete']);
Route::options('/location/update/{location}', function () {
    return response()->json(null, 200)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'PUT,GET,DELETE,POST')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
});
  1. 第二个控制器的路由:
Route::options('/land/add', [landController::class,'handleCorsPreflight']);
Route::get('/land/getall', [landController::class,'index']);
Route::get('/land/getbyid/{id}', [landController::class,'getById']);
Route::post('/land/add', [landController::class,'store']);
Route::put('/land/update/{land}', [landController::class,'update']);
Route::delete('/land/delete/{id}', [landController::class,'delete']);

请注意,这些代码片段是根据您提供的信息进行的翻译,如果有任何错误或需要进一步的帮助,请告诉我。

英文:

I am getting this error in my browser when I am trying to make post or put or delete request I tried to edit the response header in the controller and to have middleware but still getting the error
in one of the controllers it works for me for (get,post,delete) requests but still having the problem with the put request however here is the code of the working controller(just the post delete get)

   &lt;?php
namespace App\Http\Controllers;
use App\Models\locations;
use Illuminate\Http\Request;
class locationController extends Controller
{
public function store(Request $request){
$data = $request-&gt;validate([
&#39;name&#39;=&gt;&#39;required|min:3&#39;
]);
$response = [
&#39;returnCode&#39;=&gt;200,
&quot;errorMsg&quot;=&gt;&quot;&quot;,
&quot;result&quot;=&gt;locations::create($data)
];
return response()-&gt;json($response,200)-&gt;header(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;)
-&gt;header(&#39;Access-Control-Allow-Methods&#39;, &#39;POST, GET, OPTIONS, PUT, DELETE&#39;)
-&gt;header(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type, Authorization&#39;);
}
public function delete($id){
$location = locations::destroy($id);
$response = [
&#39;returnCode&#39;=&gt;200,
&quot;errorMsg&quot;=&gt;&quot;&quot;,
&quot;result&quot;=&gt;$location
];
return response($response,200)-&gt;header(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;)
-&gt;header(&#39;Access-Control-Allow-Methods&#39;, &#39;POST, GET, OPTIONS, PUT, DELETE&#39;)
-&gt;header(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type, Authorization&#39;);  
}
public function update(locations $location,Request $request){
$data = $request-&gt;validate([
&#39;name&#39;=&gt;&#39;required&#39;,
]);
$location-&gt;update($data);
$location-&gt;save();
$response = [
&#39;returnCode&#39;=&gt;200,
&quot;errorMsg&quot;=&gt;&quot;&quot;,
&quot;result&quot;=&gt;$location
];
return response($response,200)-&gt;header(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;)
-&gt;header(&#39;Access-Control-Allow-Methods&#39;, &#39;POST, GET, OPTIONS, PUT, DELETE&#39;)
-&gt;header(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type, Authorization&#39;);  
}
public function getById($id){
$response = [
&#39;returnCode&#39;=&gt;200,
&quot;errorMsg&quot;=&gt;&quot;&quot;,
&quot;result&quot;=&gt;locations::find($id)`your text`
];
return response($response,200);
}
public function index(){
$response = [
&#39;returnCode&#39;=&gt;200,
&quot;errorMsg&quot;=&gt;&quot;&quot;,
&quot;result&quot;=&gt;locations::all()
];
return response($response,200);
}
}

and here is the routes for the same controller


Route::get(&#39;/location/getall&#39;,[locationController::class,&#39;index&#39;]);
Route::get(&#39;/location/getbyid/{id}&#39;,[locationController::class,&#39;getById&#39;]);
Route::post(&#39;/location/add&#39;,[locationController::class,&#39;store&#39;]);
Route::put(&#39;/location/update/{location}&#39;,[locationController::class,&#39;update&#39;]);
Route::delete(&#39;/location/delete/{id}&#39;,[locationController::class,&#39;delete&#39;]);
Route::options(&#39;/location/update/{location}&#39;, function () {
return response()-&gt;json(null, 200)
-&gt;header(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;)
-&gt;header(&#39;Access-Control-Allow-Methods&#39;, &#39;PUT,GET,DELETE,POST&#39;)
-&gt;header(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type, Authorization&#39;);
});

here is the controller code that's not working for any(put, delete,post)

namespace App\Http\Controllers;
use App\Models\Lands;
use App\Models\locations;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\QueryBuilder\QueryBuilder;
use function PHPSTORM_META\map;
class landController extends Controller
{
public function store(Request $request){
$data = $request-&gt;validate([
&#39;ownerName&#39;=&gt;&#39;required&#39;,
&#39;size&#39;=&gt;&#39;required&#39;,
&#39;price&#39;=&gt;&#39;required&#39;,
&#39;phoneNumber&#39;=&gt;&#39;required&#39;,
&#39;locations_id&#39;=&gt;&#39;required&#39;,
&#39;aquariumNumber&#39;=&gt;&#39;required&#39;,
&#39;partNumber&#39;=&gt;&#39;required&#39;,
&#39;streetNumber&#39;=&gt;&#39;required&#39;,
&#39;streetWide&#39;=&gt;&#39;required&#39;
]);
$land = Lands::create($data);
$response = [
&#39;returnCode&#39;=&gt;200,
&quot;errorMsg&quot;=&gt;&quot;&quot;,
&quot;result&quot;=&gt;$land
];
return response($response, 200)
-&gt;header(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;)
-&gt;header(&#39;Access-Control-Allow-Methods&#39;, &#39;POST, GET, OPTIONS, PUT, DELETE&#39;)
-&gt;header(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type, Authorization&#39;);
}
//    public function search(Request $request){
//     //return locations::where(&#39;&#39;,&#39;LIKE&#39;,&quot;%$request-&gt;name%&quot;)-&gt;get();
// }
public function index(Request $request){
$lands = lands::with([&#39;locations&#39;])-&gt;get();
$response = [
&#39;returnCode&#39;=&gt;200,
&quot;errorMsg&quot;=&gt;&quot;&quot;,
&quot;result&quot;=&gt;$lands
];
return response($response,200);
}
public function getById($id){
$lands = lands::with([&#39;locations&#39;])-&gt;find($id);
$response = [
&#39;returnCode&#39;=&gt;200,
&quot;errorMsg&quot;=&gt;&quot;&quot;,
&quot;result&quot;=&gt;$lands
];
return response($response,200); 
}
public function handleCorsPreflight()
{
return response(null,200)
-&gt;header(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;)
-&gt;header(&#39;Access-Control-Allow-Methods&#39;, &#39;POST, GET, OPTIONS, PUT, DELETE&#39;)
-&gt;header(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type, Authorization&#39;);
}
public function delete($id){
$lands = lands::destroy($id);
$response = [
&#39;returnCode&#39;=&gt;200,
&quot;errorMsg&quot;=&gt;&quot;&quot;,
&quot;result&quot;=&gt;$lands
];
return response($response,200);  
}
public function update(Lands $land,Request $request){
$data = $request-&gt;validate([
&#39;ownerName&#39;=&gt;&#39;required&#39;,
&#39;size&#39;=&gt;&#39;required&#39;,
&#39;price&#39;=&gt;&#39;required&#39;,
&#39;phoneNumber&#39;=&gt;&#39;required&#39;,
&#39;locations_id&#39;=&gt;&#39;required&#39;,
&#39;aquariumNumber&#39;=&gt;&#39;required&#39;,
&#39;partNumber&#39;=&gt;&#39;required&#39;,
&#39;streetNumber&#39;=&gt;&#39;required&#39;,
&#39;streetWide&#39;=&gt;&#39;required&#39;
]);
$land-&gt;update($data);
$land-&gt;save();
$response = [
&#39;returnCode&#39;=&gt;200,
&quot;errorMsg&quot;=&gt;&quot;&quot;,
&quot;result&quot;=&gt;$land
];
return response($response,200);  
}

and here is the routing for the same controller

`
`Route::options(&#39;/land/add&#39;, [landController::class,&#39;handleCorsPreflight&#39;]);
Route::get(&#39;/land/getall&#39;, [landController::class,&#39;index&#39;]);
Route::get(&#39;/land/getbyid/{id}&#39;, [landController::class,&#39;getById&#39;]);
Route::post(&#39;/land/add&#39;, [landController::class,&#39;store&#39;]);
Route::put(&#39;/land/update/{land}&#39;, [landController::class,&#39;update&#39;]);
Route::delete(&#39;/land/delete/{id}&#39;, [landController::class,&#39;delete&#39;]);``

finnaly here is the error code

Access to XMLHttpRequest at 'https://swift-serv.com/api/land/add/' from origin 'https://house-land-asem.000webhostapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

***some note
I am using hostinger for laravel and 000webhost for the angular

thank you for your help and sorry if I wrote too much

答案1

得分: 0

I had the same CORS problem when working with Angular and PHP. I think your problem can be solved by adding an Access-Control-Allow-Origin header to your PHP file. You can start by allowing everything to check if your setup works and then customize it to allow as little access as possible. Try the following code:

<?php
header('Access-Control-Allow-Origin: *');
namespace App\Http\Controllers;

use App\Models\locations;
use Illuminate\Http\Request;

class locationController extends Controller
{
    // ...
}
?>

If this works, you can replace the star (*) with your specific needs. I hope this helps. You can also check out the following video that helped me a lot back then: Link

英文:

i had the same cors-problem when working with angular and php. I think your Problem can be solved by adding an Access-Control-Allow-Origin Header to your php file. You can start by allowing everything, to check if your setup works and then customize to as little access as possible. Try the following code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

  &lt;?php
header(&#39;Access-Control-Allow-Origin: *&#39;);
namespace App\Http\Controllers;
use App\Models\locations;
use Illuminate\Http\Request;
class locationController extends Controller
{...}
?&gt;

<!-- end snippet -->

If this works you can replace the Star to your needs. I hope this helps. You can also check out the following video which helped me a lot back then Laravel 和 Angular 的跨域来源问题 https://www.youtube.com/watch?v=IAJpoH3-Ap8&amp;ab_channel=StandaloneDeveloper

huangapple
  • 本文由 发表于 2023年6月6日 06:44:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定