简体   繁体   English

我的 Angular MEAN STACK 应用程序无法从我的 API 接收/读取 HTTP 请求?

[英]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.

相关问题 我似乎无法从我的快递 API 接收图像 - I cannot seem to receive images from my express API 在网络上部署使用MEAN堆栈构建的Web应用程序 - Deploying my web application built using MEAN stack on the web 无法从mongodb集合中删除角度MEAN堆栈 - Cannot delete from mongodb collection angular MEAN stack 无法让我的 Node.js 服务器接收来自 cURL 的 HTTP 请求 - Cannot get my Node.js server to receive HTTP request from cURL 我使用JavaScript收到API的404 HTTP错误,但未在终端中收到 - I receive a 404 HTTP error with an API using javascript but not in my terminal 在我从 controller 接收数据之前,如何在我的 Angular 应用程序中处理来自 html 的未定义属性? - How do I handle undefined properties from the html in my Angular application before I receive data from my controller? MEAN Stack:无法读取未定义的属性“ companyTitle” - MEAN Stack: Cannot read property 'companyTitle' of undefined 在MERN堆栈应用程序中创建了无数HTTP请求 - Countless http requests created in MERN stack application 当我设计我的First Mean堆栈UI时,我的Basic Angular App失败了 - My Basic Angular App failing me when i'm designing my First Mean stack UI 为什么我在 Angular 应用程序的浏览器控制台中看到 Cannot read properties of undefined (reading 'indexOf') - why does I'm seeing Cannot read properties of undefined (reading 'indexOf') in my browser console for Angular application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM