简体   繁体   中英

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

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:

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:

   <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)

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.

You can resolve this using 'cors' npm package.

Install it as a local dependency:

 npm install cors --save

Add it as a middleware to the app.

The updated code after adding 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.

This is a duplicate to How to enable cors nodejs with express?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM