我的项目在服务器上,出现此错误
“从原点“ http://example.com/testapi”对“ http://example.com”处XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态。
和“ OPTIONS http://example.com/testapi 405(不允许使用方法)”
前端是 Angular7 ,后端是 PHP
teamservice.ts
node_modules
component.ts
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from 'rxjs';
const httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*',
'Content-Type': 'application/json'
})
};
@Injectable()
export class TeamService {
constructor(private http: HttpClient) {
}
getTeams(): Observable<any> {
var urlPrefix = "http://demomewhy.com/testapi";
return this.http.get<any>(urlPrefix, httpOptions);
}
}
.htaccess
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor(private teamService: TeamService) { }
ngOnInit() {
this.loadTeams();
}
loadTeams() {
this.teamService.getTeams().subscribe(data => {
console.log(data);
//this.teamData = data;
})
}
proxy.conf.json
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond % { HTTP: Authorization }.
RewriteRule.* -[E = HTTP_AUTHORIZATION:% { HTTP: Authorization }]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>