简体   繁体   中英

CORS - Lumen and Angular request

I have an Angular app running at http://localhost:4200 and a Lumen API running at http://localhost:8000 .

I'm using barryvdh/laravel-cors and all my POSTS requests returns "No 'Access-Control-Allow-Origin' header is present on the requested resource."

Any clues about that? My Angular Database Service:

@Injectable()
export class DatabaseService {

  constructor(private http: Http) { }

  get(url: string) {
    return this.http.get("http://localhost:8000/" + url)
      .map(response => response.json());
  }

  post(url: string, data) {
    return this.http.post("http://localhost:8000/"+ url, data)
      .map(response => response.json());
  }

}

All GET requests work properly.

Enabling apache mod_headers will fix this issue. Run below commands

  1. a2enmod headers
  2. sudo service apache2 restart

It depends on the data you pass and how you handle in the back-end. did you try stringifying data

JSON.stringify(data)

post(url: string, data) {
return this.http.post("http://localhost:8000/"+ url, JSON.stringify(data))
  .map(response => response.json());
}

You need to grant access to your Angular server on Lumen

If you are not using CORS Just add this line on /bootstrap/app.php

header('Access-Control-Allow-Origin: http://localhost:4200/');

or for everyone:

header('Access-Control-Allow-Origin: *');

If you are using CORS you must set the same thing on the headers on App\\Http\\Middleware\\CorsMiddleware (or whatever is called your CORS file)

$headers = [
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
        ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM