Angular 5调用WebApi时遇HTTP GET方法不允许问题求助
Let's walk through why this is happening and get your request working smoothly:
The Core Issue: Misplaced CORS Headers
First off, a critical misunderstanding here: those Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers headers you're sending in your request don't belong there. These are response headers that the server sends back to the browser to approve cross-origin requests—you shouldn't include them in your frontend request. When you do, the server sees them as invalid or unexpected, which is likely triggering the 405 Method Not Allowed error.
On top of that, setting Content-Type: text/xml on a GET request is unusual (GET requests typically don't have a request body, so this header is often unnecessary). This could also be confusing the server's request validation logic.
Corrected LoginService Code
Here's the revised service with the problematic headers stripped out. I've kept only the minimal necessary configuration (you can even omit the headers entirely if your server accepts default request headers):
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable() export class LoginService { constructor(private http: HttpClient) {} getUsers() { // Only include headers if your server explicitly requires them const options = { headers: new HttpHeaders({ // Remove all Access-Control-* headers entirely // Keep this only if your server specifically expects XML; otherwise, use application/json or omit 'Content-Type': 'text/xml' }) }; return this.http.get('myurl', options); } }
Additional Troubleshooting Steps
If you still hit the 405 error after fixing the headers, check these:
- Verify that your
myurlpoints to a valid server endpoint that explicitly supports the GET method. Double-check the server's API docs or routing configuration to confirm. - Confirm the server's CORS setup is correct: it should allow requests from your frontend's domain, and list GET as an allowed HTTP method.
- Check the server's error logs—they'll usually give specific details about why the request was rejected (e.g., invalid headers, unsupported method for that endpoint).
内容的提问来源于stack exchange,提问作者Ivan-Mark Debono

