当Angular应用程序通过CORS预检请求发送请求时,服务器可能会出现400 Bad Request错误,但是使用Postman发送相同的请求却没有问题。这个问题通常是由于请求头中的某些参数或值不正确导致的。
为了解决这个问题,你可以尝试以下解决方案:
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer your-auth-token'
})
};
http://example.com/api
,则Angular应用程序中的请求也应该是相同的。import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) {}
postData() {
const url = 'http://example.com/api';
const data = { name: 'John Doe' };
this.http.post(url, data).subscribe(response => {
console.log(response);
});
}
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
// ... handle other routes
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
这些解决方案应该可以帮助你解决Angular的CORS预检请求导致400 Bad Request错误的问题。如果问题仍然存在,请检查服务器端的日志以获取更多详细信息。