Я пытаюсь сделать глупость со средним стеком, вопрос, который я не понимаю, потому что он не добавляет мне задачи.

Мой app.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

const server = express();

// connect mongodb
mongoose.connect('mongodb://localhost:27017/myDb', { useNewUrlParser: true, useUnifiedTopology: true }).
    then(() => { console.log('DB is connected') },
        err => { console.log('Can not connect to the database' + err) });

// routes
const taskRoutes = require('./routes/task');

server.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "http://localhost:3000");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept"
    );
    res.header("Access-Control-Allow-Methods", "HEAD, GET, POST, OPTIONS, PUT, DELETE");
    next();
});


server.use('/task', taskRoutes);
server.get('/', (req, res) => {
    res.send("New Tasks");
});

server.use(bodyParser.json());
server.use(cors);


// server initialization
server.listen(3000, () => {
    console.log("________________________________________________________");
    console.log("||-->          Server running on port 3000         <--||");
    console.log("TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT");
});

Моя модель:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Task = new Schema({
    name: {
        type: String
    },
}, {
    collection: 'task'
});

module.exports = mongoose.model('Task', Task);

Мой маршрут:

const server = require('express').Router();

const Task = require('../models/Task');

// add task
server.post('/add', (req, res) => {
    let task = new Task(req.body);
    task.create()
        .then(todo => {
            res.status(200).json({ 'status': 'success', 'mssg': 'task added successfully' });
        })
        .catch(err => {
            res.status(409).send({ 'status': 'failure', 'mssg': 'unable to save to database' });
        });
});

// get tasks
server.get('/', (req, res) => {
    Task.find((err, tasks) => {
        if (err) {
            res.status(400).send({ 'status': 'failure', 'mssg': 'Something went wrong' });
        }
        else {
            res.status(200).json({ 'status': 'success', 'tasks': tasks });
        }
    });
});

// edit task
server.get('/edit/:id', (req, res) => {
    let id = req.params.id;
    Task.findById(id, (err, task) => {
        if (err) {
            res.status(400).send({ 'status': 'failure', 'mssg': 'Something went wrong' });
        }
        else {
            res.status(200).json({ 'status': 'success', 'task': task });
        }
    });
});

// update task
server.put('/update/:id', (req, res) => {
    Task.findById(req.params.id, (err, task) => {
        if (!task) {
            res.status(400).send({ 'status': 'failure', 'mssg': 'Unable to find data' });
        } else {
            task.name = req.body.name;

            task.update().then(work => {
                res.status(200).json({ 'status': 'success', 'mssg': 'Update complete' });
            })
        }
    });
});

// delete task
server.delete('/delete/:id', (req, res) => {
    Task.destroy({ _id: req.params.id }, (err,) => {
        if (err) {
            res.status(400).send({ 'status': 'failure', 'mssg': 'Something went wrong' });
        }
        else {
            res.status(200).json({ 'status': 'success', 'mssg': 'Delete successfully' });
        }
    });
});

module.exports = server;

Мой add.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { TaskService } from '../task.service';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css'],
})
export class AddComponent implements OnInit {
  response: any = {};
  angForm: FormGroup;
  constructor(private fb: FormBuilder, private tas: TaskService) {
    this.angForm = this.fb.group({
      name: ['', Validators.required],
    });
  }

  ngOnInit() {}

  addTask() {
    this.tas.addTask(this.angForm.value).subscribe((res) => {
      this.response = res;
      if (this.response.status == 'success') {
        this.tas.alert('Task added successfully!', 'success');
        this.angForm.reset();
      } else {
        this.tas.alert('Error saving task!', 'error');
      }
    });
  }
}

Мой add.component.html

<div class="card">
  <div class="card-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4 title-add">Title</label>
        <input type="text" class="form-control" formControlName="name" #name />
      </div>
      <div *ngIf="angForm.controls['name'].invalid && angForm.controls['name'].touched" class="alert alert-danger">
        <div *ngIf="angForm.controls['name'].errors.required">
          Title is required.
        </div>
      </div>
      <div class="form-group">
        <button type="submit" (click)="addTask()" [disabled]="angForm.pristine || angForm.invalid"
          class="btn btn-primary">Add Task</button>
      </div>
    </form>
  </div>
</div>

Когда я нажимаю кнопку «добавить задачу» компонента add.component.html, я получаю в консоли браузера следующее:

Access to XMLHttpRequest at 'http://localhost:3000/task/add' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3000' that is not equal to the supplied origin.
zone-evergreen.js:2845 POST http://localhost:3000/task/add net::ERR_FAILED
scheduleTask @ zone-evergreen.js:2845
scheduleTask @ zone-evergreen.js:385
onScheduleTask @ zone-evergreen.js:272
scheduleTask @ zone-evergreen.js:378
scheduleTask @ zone-evergreen.js:210
scheduleMacroTask @ zone-evergreen.js:233
scheduleMacroTaskWithCurrentZone @ zone-evergreen.js:1134
(anonymous) @ zone-evergreen.js:2878
proto.<computed> @ zone-evergreen.js:1449
(anonymous) @ http.js:1776
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
innerSubscribe @ innerSubscribe.js:67
_innerSub @ mergeMap.js:57
_tryNext @ mergeMap.js:51
_next @ mergeMap.js:34
next @ Subscriber.js:49
(anonymous) @ subscribeToArray.js:3
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ mergeMap.js:19
subscribe @ Observable.js:23
call @ filter.js:13
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
addTask @ add.component.ts:22
AddComponent_Template_button_click_10_listener @ add.component.html:14
executeListenerWithErrorHandling @ core.js:15214
wrapListenerIn_markDirtyAndPreventDefault @ core.js:15249
(anonymous) @ platform-browser.js:582
invokeTask @ zone-evergreen.js:399
onInvokeTask @ core.js:27474
invokeTask @ zone-evergreen.js:398
runTask @ zone-evergreen.js:167
invokeTask @ zone-evergreen.js:480
invokeTask @ zone-evergreen.js:1621
globalZoneAwareCallback @ zone-evergreen.js:1647
Show 8 more frames
core.js:4352 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:3000/task/add", ok: false, …}

Спасибо и извините, что пост стал длинным.

0
Marcelo Del Valle 7 Окт 2020 в 15:18

1 ответ

Лучший ответ

Ваша настройка заголовка cors неверна. Поскольку ваш интерфейс работает на порту 4200, вам необходимо разрешить этот источник. Поэтому вместо порта localhost:3000 используйте:

res.header("Access-Control-Allow-Origin", "http://localhost:4200");

Также вам необходимо исправить настройку промежуточного программного обеспечения и инициализировать парсеры перед обработчиками запросов, поскольку req.body будет неопределенным в обработчике запросов с вашим текущим кодом:

server.use(bodyParser.json());
server.use(cors);

server.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "http://localhost:3000");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.header("Access-Control-Allow-Methods", "HEAD, GET, POST, OPTIONS, PUT, DELETE");
  next();
});


server.use('/task', taskRoutes);
server.get('/', (req, res) => {
    res.send("New Tasks");
});
0
eol 9 Окт 2020 в 05:46