Reputation: 2677
My post request just doesn't work when submitting data to a Laravel action. I am brand new to Angular. By doesn't work I mean the request is made but I get 500 error and the row isn't inserted in the database.
In angular I have a form component that defines this method. The method is executed then the submit button is pressed.
send(form: any): void
{
this.http.post('http://www.example.com.br/services/sendMessage', { "subject": "static subject" }).subscribe((res: Response) => { });
}
My Laravel action is this
public function sendMessage(Request $request)
{
$subject= $request->input("subject");
//code omitted for brevity
}
I performed a test with Fiddler and it worked after I added "Content-Type: application/json" (I get 500 error but the row is inserted). so I tried to add a content type to my post request in Angular but it didn't work. I looked at the request header provided by developer window of Firefox but it seems that it didn't set the content type.
send(form: any): void
{
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
this.http.post('http://www.example.com.br/services/sendMessage', { "subject": "static subject" }, options).subscribe((res: Response) => { });
}
Could the issue be CORS?
when the button of my form component is clicked I get this in the browser console
ERROR Object { _body: error, status: 0, ok: false, statusText: "", headers: Object, type: 3, url: null }
Upvotes: 0
Views: 731
Reputation: 3905
here is what you can do there is a helpful package called laravel-cors which allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration. cross-origin issue basiclly occurs when you make http requests from a different domain.
the installation process:
composer require barryvdh/laravel-cors
then Add the Cors\ServiceProvider to your config/app.php providers array:
Barryvdh\Cors\ServiceProvider::class,
in your pp/Http/Kernel.php add this to your $middleware array
protected $middleware = [
// ...
\Barryvdh\Cors\HandleCors::class, // add this
];
You can publish the config using this command:
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
Upvotes: 1