问题描述: 在Angular 9中,发起POST请求时遇到问题,无法正常工作。
解决方法:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule
],
...
})
export class AppModule { }
import { HttpClient } from '@angular/common/http';
@Injectable()
export class MyService {
constructor(private http: HttpClient) { }
postData(data: any) {
const url = 'https://example.com/api';
console.log('URL:', url);
console.log('Data:', data);
return this.http.post(url, data);
}
}
// Express.js示例
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://example.com');
res.setHeader('Access-Control-Allow-Methods', 'POST');
next();
});
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class MyService {
constructor(private http: HttpClient) { }
postData(data: any) {
const url = 'https://example.com/api';
const headers = new HttpHeaders().set('Content-Type', 'application/json');
return this.http.post(url, data, { headers });
}
}
通过检查以上几点,您应该能够解决Angular 9无法发起POST请求的问题。如果问题仍然存在,请尝试在浏览器的开发者工具中查看网络请求和响应,以获取更多的调试信息。