http - http请求在邮递员中有效,但在浏览器中无效
问题描述
我能够发送帖子并从邮递员那里获取请求,但是当我实际从浏览器发送该请求时,它无法获取记录,并且在控制台中显示错误“正文:{错误:“未找到集合'未定义'}”。
尝试了 Get 和 Post 请求,它们都在 POSTMAN 中提供数据作为响应,但在浏览器中它不起作用。显示错误“body: {error: "Collection 'undefined' not found"}”。在不同地方的同一个项目中,我也使用内存数据库,我可以对其进行 /GETRequest 并接收数据作为响应。
homepage.ts:=============
public AllItem: AllItems[] ;
getAllItems(): void {
console.log('AA');
this.itemService.getAllItems() //(this.AllItems)
.subscribe(AllItem => this.AllItem = AllItem );
console.log(this.AllItem);
console.log('EE');
}
item.Service.ts:===============
private itemsUrl = 'api/items'; // URL to web api
private allItemsUrl = 'http://*************.azurewebsites.net/items';
getAllItems(): Observable<AllItems[]>{
console.log('CC');
return this.http.get<AllItems[]>(this.allItemsUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<AllItems[]>('getHeroes', []))
);
}
// this get request work properly and gives response data from in-memoery-db
getItems(): Observable<Item[]> {
return this.http.get<Item[]>(this.itemsUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<Item[]>('getHeroes', []))
);
}
in POSTMAN it gives data as
{
"items": [
{
"category": "Drink",
"item": "Coffee",
"price": "5$"
}]
}
in Browser console
core.js:15724 ERROR
body: {…}, url: "http://**********.azurewebsites.net/items", headers: HttpHeaders, status: 404, statusText: "Not Found"}
body: {error: "Collection 'undefined' not found"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 404
statusText: "Not Found"
url: "http://*************.azurewebsites.net/items"
__proto__: Object
解决方案
得到了解决方案,实际上我在同一个项目的其他地方使用了 in-memory-web-api,未找到集合错误表明您以前使用过 angular-in-memory-web-api。您需要从项目中删除与此相关的所有内容,以便能够使用外部 api 和 db。
“InMemoryWebApiModule.forRoot(InMemoryDataService)” Angular in-memory-web-api,它替换了 HttpClient 模块的 HttpBackend 所以在使用实际服务器和数据库之前需要先删除它
在此之后,我面临另一个问题,即对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
为此,我们需要在 Azure 的节点服务器中使用以下内容。var cors = require('cors'); app.use(cors({origin: '*'}));
推荐阅读
- python - 在python中声明变量
- python - tf.data.Dataset 的扩充
- firebase - 运行依赖于 firestore 模拟器的 CI 测试
- php - Laravel - spatie 权限删除 phpunit 中的权限问题
- java - 如何在 Java 中使用重音符号进行排序
- javascript - 在 Var 赋值期间更新全局变量
- azure - 流程:从引用 URL 解析变量
- python - Apache Beam GroupByKey 不产生任何输出
- node.js - 新在 node-red 的功能块中不起作用
- c++ - Visual Studio 2019 - 在本地(而不是远程)调试 C++ 程序