gpt4 book ai didi

Angular http.get header 未被识别

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:47 27 4
gpt4 key购买 nike

我正在构建一个 Angular 6 应用程序,它通过 REST API 向服务器发送一个 get 请求。该 URL 接受一些 header 并返回所需的数据,并已在 PostMan 上成功测试。这是显示服务器所需 header 的屏幕截图:

Post Man image

我正在尝试使用 http.get 创建一个函数,以便在我的应用程序中检索这些记录。我已经创建了一个名为 listService 的服务,它会接收模块名称并准备一个 header 对象。然后该服务将调用 adapterService(包含我的 get 函数),它会准备 header 并将请求发送到服务器。不幸的是,我没有收到有效的回复,而是收到以下错误:

"SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:13170:51) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2743:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:42628:33) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2742:36) at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2510:47) at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:2818:34) at invokeTask (http://localhost:4200/polyfills.js:3862:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:3888:17)"

从服务器添加日志后,我注意到请求中发送的 header :

 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。我真的不明白这是怎么回事。

这是我的代码:

列表服务

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( header 和获取函数)

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 之前了解 header 对象的外观的人:

picture

另一个编辑可能是 CORS 导致了问题吗?我已将 Access-Control-Allow-Origin 设置为“*”。这是我提出更改后的网络事件:

result

正在访问 REST 服务,但它没有将我重定向到我的 API

当我通过 postman 发送时,服务器上记录的标题是:

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
)

并且这些正在正常工作

最佳答案

get(path: string, data: any, params: HttpParams = new HttpParams()): Observable < any > {
let httpOptions ={headers: this.requestHeaders(path, data)};
return this.http.get(`${API_URL}${path}`, httpOptions)
.pipe(catchError(this.formatErrors));
}

试试看。您需要传递一个包含 headers 属性的选项对象。

https://angular.io/guide/http#adding-headers

关于Angular http.get header 未被识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55255001/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com