[英]My Angular MEAN STACK Application cannot receive/read HTTP Requests from my API?
error Firstly, I created an API that would do get and post: more error错误首先,我创建了一个可以获取和发布的 API:更多错误
const express = require('express');
const router = express.Router();
const model = require('../models/taskModel');
router.get('/tasks', (req, res) => {
model.find()
.then((task) => {
res.json(task);
console.log(task);
})
.catch((err) => {
console.log(`Error: ${err}`);
})
})
router.post('/add', (req, res) => {
const userData =
{
title: req.body.title,
description: req.body.description,
isDone: req.body.isDone
}
const newUser = new model(userData);
newUser.save()
.then(() => res.json('User Added!'))
.catch((err) => {
console.log(`Cannot add user: ${err}`);
})
}) })
I have a service file that looks something like this:我有一个看起来像这样的服务文件:
import { Injectable } from '@angular/core';
import { taskData } from '../Models/task-interface';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
// Http
const httpOptions = {
headers: new HttpHeaders({ 'Content-type': 'application/json' })
}
@Injectable({
providedIn: 'root'
})
export class RequestsService {
tasks: taskData[];
key: string = `http://localhost:5000/api/tasks`;
constructor(private http: HttpClient) { }
getTasks(): Observable<taskData[]> {
return this.http.get<taskData[]>(this.key);
}
}
I am then calling the 'getTasks()' function from my service module inside my component:然后,我从组件内的服务模块调用“getTasks()”函数:
import { Component, OnInit } from '@angular/core';
import { RequestsService } from '../../Services/requests.service';
import { taskData } from '../../Models/task-interface';
@Component({
selector: 'app-tasks',
templateUrl: './tasks.component.html',
styleUrls: ['./tasks.component.css']
})
export class TasksComponent implements OnInit {
tasks: taskData[];
constructor(private reqService: RequestsService) {
}
ngOnInit() {
this.reqService.getTasks().subscribe((data: taskData[]) => {
this.tasks = data;
console.log(`This is my log: ${this.tasks}`);
})
}
}
Inside my component.html, i am using ngFor to go through the tasks and get each task from my mongoDB database:在我的 component.html 中,我使用 ngFor 来完成任务并从我的 mongoDB 数据库中获取每个任务:
<div class="d-flex justify-content-around align-items-center" *ngFor="let task of tasks">
<input type="checkbox" name="" id="">
<h2 class="text-center">{{task.title}}</h2>
<p class="text-center">{{task.description}}</p>
<button class="btn btn-danger">Delete Task</button>
</div>
This is the error message that i get when i run this app.这是我运行此应用程序时收到的错误消息。 (ps the get and post requests work in postman but apparently cant be read by my angular app) (ps get 和 post 请求在邮递员中工作,但显然我的 angular 应用程序无法读取)
FORGOT TO SHOW MY MODEL:忘了展示我的模型:
export interface taskData {
title: string,
description: string,
isDone: boolean
}
You are able to get response using postman because there is no Cross Origin issue in that case.您可以使用邮递员获得回复,因为在这种情况下不存在跨域问题。
When you try to get the response using your browser, there is a difference in the origins of the app and the api so it leads to CORS issue.当您尝试使用浏览器获取响应时,应用程序和 api 的来源存在差异,因此会导致CORS问题。
You can resolve this using 'cors' npm package.您可以使用“cors” npm 包解决此问题。
Install it as a local dependency:将其安装为本地依赖项:
npm install cors --save
Add it as a middleware to the app.将其作为中间件添加到应用程序中。
The updated code after adding cors:添加cors后的更新代码:
const express = require('express');
const router = express.Router();
const model = require('../models/taskModel');
const cors = require('cors');
let app = express();
app.use(cors());
router.get('/tasks', (req, res) => {
model.find()
.then((task) => {
res.json(task);
console.log(task);
})
.catch((err) => {
console.log(`Error: ${err}`);
})
})
router.post('/add', (req, res) => {
const userData =
{
title: req.body.title,
description: req.body.description,
isDone: req.body.isDone
}
const newUser = new model(userData);
newUser.save()
.then(() => res.json('User Added!'))
.catch((err) => {
console.log(`Cannot add user: ${err}`);
})
This will enable CORS (Cross-Origin-Resource-Sharing) to your node app.这将为您的节点应用程序启用CORS(跨源资源共享) 。
This is a duplicate to How to enable cors nodejs with express?这与如何使用 express 启用 cors nodejs重复?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.