Угловая загрузка файла 2 с помощью node.js - PullRequest
0 голосов
/ 01 ноября 2018

Я пытаюсь сделать функцию загрузки файла. Я использую Node.js, Anugular2 +, mongoDB, экспресс.

В форме есть {title, author, file}, и я импортировал это, чтобы загрузить файл.

import { FileUploadModule } from "ng2-file-upload";

Я не знаю, где эта ошибка происходит на стороне сервера или угловой. или проблема URL в компоненте?

это полный журнал ошибок

t {headers: e, status: 500, statusText: "Internal Server Error", url: "http://localhost:3000/api/board", ok: false, …}
error: {status: 500, message: "response is not defined", name: "ReferenceError"}
headers: e {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:3000/api/board: 500 Internal Server Error"
name: "HttpErrorResponse"
ok: false
status: 500
statusText: "Internal Server Error"
url: "http://localhost:3000/api/board"
__proto__:
constructor: ƒ t(t)
__proto__: Object

Node.js

api.js

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Board = require('../models/Board.js');
var app = express();
var multer = require('multer');

var _storage = multer.diskStorage({
  destination: function(req, file, cd){
    cb(null, 'upload/');
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  }

});
var upload = multer({storage: _storage});


app.use('/user', express.static('upload/'));
// API ROOT ROUTE
router.get('/', (req, res) => {
    res.status(200).json({ status: 200, result: 'success' });
});

// GET A Board
router.get('/board/:id', (req, res, next) => {
    Board.findById(req.params.id, (err, post) => (err) ? next(err) : res.json(post));
});

// SAVE A Board
router.post('/board', upload.single('file'),  (req, res, next) => {
    console.log(req.file);
    response.type("application/json");
    response.send({
      result:true,
      originalname: req.file.originalname,
      filename:req.file.filename
    })
    Board.create(req.body, (err, post) => (err) ? next(err) : res.json(post));
});


module.exports = upload;
module.exports = router;

Angular2 плата-create.component.html

<form #boardForm="ngForm" (ngSubmit)="saveBoard()">
    <div class="field">
      <div class="control">
        <label for="title">Title</label>
        <input required name="title" id="title" [(ngModel)]="board.title" type="text" class="input">
      </div>
    </div>
    <div class="field">
      <div class="control">
        <label for="author">Author</label>
        <input required name="author" id="author" [(ngModel)]="board.author" type="text" class="input">
      </div>
    </div>

    <div class="field">
      <div class="control">
        <label for="author">file</label>
        <input accept="image/*" name="file" ng-value="fileToUpload" value="{{fileToUpload}}" file-model="fileToUpload" [(ngModel)]="board.file"
               set-file-data="fileToUpload = value;"    type="file" id="my_file" ng2FileSelect [uploader]="uploader" />
      </div>
    </div>

    <div class="field">
      <div class="control">
        <button class="button is-warning" routerLink="/boards"><i class="fas fa-arrow-left"></i>Back</button>
        <button class="button is-link" type="submit" [disabled]="!boardForm.valid">Create</button>
      </div>
    </div>

  </form>

доска-create.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { BoardService } from '../../services/board.service';
import { Board } from '../../models/Board';
import {  FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';
import {FileUploadModule} from "ng2-file-upload";


const URL = 'http://localhost:3000/board-create';

@Component({
  selector: 'app-board-create',
  templateUrl: './board-create.component.html',
  styles: []
})
export class BoardCreateComponent {

  public uploader: FileUploader = new FileUploader({
    url:URL, itemAlias: 'file'
  })
  fileInfo = {
    originalname:'',
    filename:''
  }

  board: any = {};
  fileToUpload: any;
  constructor(private router: Router, private boardService: BoardService) {

    this.uploader.onCompleteItem=(item, response, status, header)=> {
      this.fileInfo=JSON.parse(response);
    }

  }


  saveBoard() {
    console.log(this.fileInfo.originalname);
    this.boardService.insertBoard(this.board)
      .subscribe((res: Board) => { this.router.navigate(['/boards']); }, (err) => console.log(err));
  }
}

1 Ответ

0 голосов
/ 01 ноября 2018

Проблема в board post API.

В приведенном ниже коде вы использовали response.type("application/json");, который должен быть res.type ("application / json"); Также измените response.send() на res.send()

router.post('/board', upload.single('file'),  (req, res, next) => {
        console.log(req.file);
        response.type("application/json");
        response.send({
          result:true,
          originalname: req.file.originalname,
          filename:req.file.filename
        })
        Board.create(req.body, (err, post) => (err) ? next(err) : res.json(post));
    });
...