带有Java servlet的Angular 4 http CORS否'Access-Control-Allow-Origin' [英] Angular 4 http CORS No 'Access-Control-Allow-Origin' with a java servlet
问题描述
我正在尝试执行http.post,但是chrome显示以下错误:
I'm trying to do a http.post but chrome is showing the following error:
没有访问控制权限来源.
No Access-Control-Allow-Origin.
我的Angular函数是:
My Angular function is:
onSubmit(event: Event) {
event.preventDefault();
this.leerDatos()
.subscribe(res => {
//datos = res.json();
console.log("Data send");
}, error => {
console.log(error.json());
});
}
leerDatos(): Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(`http://localhost:8080/LegoRepositoryVincle/CoreServlet`, { name: "bob" }, options)
//.map(this.extractData)
//.catch(this.handleError);
}
我的servlet doPost方法包括:
And my servlet doPost method includes:
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.addHeader("Access-Control-Allow-Origin","http://localhost:4200");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Methods","GET,POST");
response.addHeader("Access-Control-Allow-Headers","X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, Cache-Control, Pragma");
推荐答案
If you still want to use CORS while developing you can solve this kind of issue using angular/cli --proxy-config.
基本上,如果要向运行例如 nginx Web服务器的远程计算机发出请求,您可以对同一个应用程序执行所有调用,例如localhost:4200
(默认为angular/cli).然后,您可以使用--proxy-config
将这些响应重定向到您的服务器.
Essentially, if you want to make requests to a remote machine having, for example, nginx web server running, you perform all your calls to your very same application, e.g. localhost:4200
(default in angular/cli). Then you redirect those responses to your server using --proxy-config
.
让我们假设您服务器的api具有所有/api
前缀入口点.您需要在项目的根目录中创建一个名为 proxy.config.json 的文件,并将其配置为:
Let's suppose your server's api have all the /api
prefix entrypoint. You need to create a file called proxy.config.json in the root of your project and configure it like:
{
"/api" : {
"target" : "http://xx.xxx.xxx.xx", // Your remote address
"secure" : false,
"logLevel" : "debug", // Making Debug Logs in console
"changeOrigin": true
}
}
然后,您的所有http请求都将指向localhost:4200/api/
.
And then, all your http requests will point to localhost:4200/api/
.
最后,您应该运行ng server --proxy-config proxy.config.json
.
如果您发现请求中缺少某些标头,请从您的Web服务器中添加标头,或编辑您的http.service.ts
以附加本示例中的标头:
If you notice that some headers are missing in the request, add them from your web server or edit your http.service.ts
to append those like in this example:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { isNull } from 'lodash';
@Injectable()
export class HttpClientService {
private _host: string;
private _authToken: string;
private _options: RequestOptions = null;
constructor(private _http: Http, private _config: AppConfig, private _localStorageService: LocalStorageService) {
this._host = ''; // Your Host here, get it from a configuration file
this._authToken = ''; // Your token here, get it from API
}
/**
* @returns {RequestOptions}
*/
createAuthorizationHeader(): RequestOptions {
// Just checking is this._options is null using lodash
if (isNull(this._options)) {
const headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
headers.append('Authorization', this._authToken);
this._options = new RequestOptions({headers: headers});
}
return this._options;
}
/**
* @param url {string}
* @param data {Object}
* @return {Observable<any>}
*/
get(url?: string, data?: Object): Observable<any> {
const options = this.createAuthorizationHeader();
return this._http.get(this._host + url, options);
}
/**
* @param url {string}
* @param data {Object}
* @return {Observable<any>}
*/
post(url?: string, data?: Object): Observable<any> {
const body = JSON.stringify(data);
const options = this.createAuthorizationHeader();
return this._http.post(this._host + url, body, options);
}
}
因此,您将通过此服务执行所有api调用,例如
So, you would perform all of your api calls through this service like
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClientService } from './http.service.ts';
export class TestComponent implements OnInit {
_observable: Observable<any> = null;
constructor(private _http: HttpClientService) { }
ngOnInit() {
this._observable = this _http.get('test/')
.map((response: Response) => console.log(response.json()));
}
}
Angular 5更新:
现在在app.module.ts
中,您需要将import { HttpModule } from '@angular/http';
替换为import { HttpClientModule } from '@angular/common/http';
.
In app.module.ts
now you need to replace import { HttpModule } from '@angular/http';
with import { HttpClientModule } from '@angular/common/http';
.
服务更改为:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { isNull, isUndefined } from 'lodash';
@Injectable()
export class HttpClientService {
private _host: string;
private _authToken: string;
private __headers: HttpHeaders;
constructor(private _http: HttpClient, private _config: AppConfig, private _localStorageService: LocalStorageService) {
this._host = ''; // Your Host here, get it from a configuration file
this._authToken = ''; // Your token here, get it from API
}
/**
* @returns {HttpHeaders}
*/
createAuthorizationHeader(): HttpHeaders {
// Just checking is this._options is null using lodash
if (isNull(this.__headers)) {
const headers = new HttpHeaders()
.set('Content-Type', 'application/json; charset=utf-8')
.set('Authorization', this. _authToken || '');
this.__headers= new RequestOptions({headers: headers});
}
return this.__headers;
}
/**
* @param url {string}
* @param data {Object}
* @return {Observable<any>}
*/
get(url?: string, data?: Object): Observable<any> {
const options = this.createAuthorizationHeader();
return this._http.get(this._host + url, {
headers : this.createAuthorizationHeader()
});
}
/**
* @param url {string}
* @param data {Object}
* @return {Observable<any>}
*/
post(url?: string, data?: Object): Observable<any> {
const body = JSON.stringify(data);
const options = this.createAuthorizationHeader();
return this._http.post(this._host + url, body, {
headers : this.createAuthorizationHeader()
});
}
}
这篇关于带有Java servlet的Angular 4 http CORS否'Access-Control-Allow-Origin'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!