【发布时间】:2019-08-10 19:21:53
【问题描述】:
我正在构建一个 Angular 6 应用程序,它通过 REST API 向服务器发送 get 请求。该 URL 包含一些标头并返回所需的数据,并已在 PostMan 上成功测试。这是显示服务器所需标头的屏幕截图:
我正在尝试使用http.get 创建一个函数,以便在我的应用程序中检索这些记录。我创建了一个名为listService 的服务,它将接收模块名称并准备一个标头对象。然后该服务将调用adapterService(包含我的get 函数),这将准备标头并将请求发送到服务器。不幸的是,我没有得到有效的响应,而是收到以下错误:
"SyntaxError: 位置 0 处 JSON 中的意外标记 http://localhost:4200/vendor.js:13170:51) 在 ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2743:31) 在 Object.onInvokeTask (http://localhost:4200/vendor.js:42628:33) 在 ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2742:36) 在 Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2510:47) 在 ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [作为调用] (http://localhost:4200/polyfills.js:2818:34) 在调用任务 (http://localhost:4200/polyfills.js:3862:14) 在 XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:3888:17)"
从服务器添加日志后,我注意到请求中发送的标头:
Wed Mar 20 11:37:43 2019 [21570][-none-][FATAL] Array
(
[Host] => localhost
[Connection] => keep-alive
[Accept] => application/json, text/plain, */*
[Origin] => http://evil.com/
[User-Agent] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36
[Referer] => http://localhost:4200/profile
[Accept-Encoding] => gzip, deflate, br
[Accept-Language] => en-US,en;q=0.9
[If-None-Match] => d41d8cd98f00b204e9800998ecf8427e
)
我发送的数据甚至没有被添加到标题中!我不确定为什么会这样。我检查了文档,看看我是否以错误的方式添加了http headers,并在各个点记录了控制台,并且一切似乎都很好直到调用http.get。我真的不明白这里发生了什么。
这是我的代码:
listService
import { Injectable } from '@angular/core';
import { JwtService } from 'src/app/services/jwt/jwt.service';
import { AdapterService } from 'src/app/services/adapter/adapter.service';
import { environment } from 'src/environments/environment';
import { NGXLogger } from 'ngx-logger';
import { Observable } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
import { TranslatePipe } from 'src/app/pipes/translate/translate.pipe';
/**
* This property contains the attributes of the environment configuration.
*/
const API = environment.api;
@Injectable({
providedIn: 'root'
})
export class ListService {
/**
* Constructor to initialize the jwt service, adapter service, logger and translation pipe
*/
constructor(private adapter: AdapterService,
private jwt: JwtService,
private translate: TranslatePipe,
private logger: NGXLogger,
private toaster: ToastrService) { }
/**
* This method initialzes the parameters for the the Get call.
*
* @param username
* @param password
* @return
*/
initializeParameters(module: string): any {
let token = this.jwt.getToken();
let params = {
"module": module,
"platform": API.platform,
"oauth_token": token
};
return params;
}
/**
* This method sends request for listing relevant data from module
*/
listData(module: string) {
let params = this.initializeParameters(module);
this.adapter.get('customPortalApi/listRecords', params)
.subscribe(
response => {
this.logger.warn(response);
},
error => {
let errmsg = this.translate.transform("pages[login_page][responses][error][" + error.error + "]");
this.toaster.error(errmsg); console.log(error);
}
)
}
}
adapterService(标头和获取函数)
private requestHeaders(path: string, headerData: any) {
let headers;
if (path !== 'customPortalApi/customToken') {
headers = new HttpHeaders();
for(let key in headerData){
let value = headerData[key];
headers = headers.append(key, value);
}
}
return headers;
}
/**
* This method generates the GET api call.
*
* @param path
* @param params
* @method get
* @return
*/
get(path: string, data: any, params: HttpParams = new HttpParams()): Observable < any > {
let headers = this.requestHeaders(path, data);
return this.http.get(`${API_URL}${path}`, headers)
.pipe(catchError(this.formatErrors));
}
虚拟组件(用于调用)
import { Component, OnInit } from '@angular/core';
import {ListService} from 'src/app/services/list/list.service';
/**
* This component is for testing
*/
@Component({
selector: 'app-dummy',
templateUrl: './dummy.component.html',
styleUrls: ['./dummy.component.scss']
})
export class DummyComponent implements OnInit{
constructor(private list: ListService){}
ngOnInit(){
this.list.listData("accounts");
}
}
EDIT适用于任何想在调用http.get之前了解标头对象外观的人:
另一个编辑
会不会是 CORS 引起了问题?我已将Access-Control-Allow-Origin 设置为“*”。这是我提出更改后的网络活动:
REST 服务被点击,但它没有将我重定向到我的 API
当我通过邮递员发送时,服务器上记录的标头是:
Wed Mar 20 12:52:50 2019 [21570][1][FATAL] Array
(
[Host] => localhost
[Connection] => keep-alive
[module] => Accounts
[Cache-Control] => no-cache
[oauth_token] => 9efe19d4d2ec3b557b4d0588a3f74d5d3cc0ed46
[platform] => base
[User-Agent] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36
[Postman-Token] => 3ddc88e1-e7a8-700f-580b-801da5f0adde
[Accept] => */*
[Accept-Encoding] => gzip, deflate, br
[Accept-Language] => en-US,en;q=0.9
[Cookie] => download_token_base=e790d5a8-17a4-4110-98ab-a6648a0ef385
)
而且这些工作正常
【问题讨论】:
-
尝试将标题传递为
this.http.get(${API_URL}${path}, {headers: headers}) -
嗨@xyz,进行了更改,但现在甚至没有对服务器进行调用,控制台显示以下错误:
Response for preflight has invalid HTTP status code 404.
标签: angular typescript rest sugarcrm