我正在使用 quill编辑器开发上传图片时遇到了帖子请求。 我不知道我要做些什么来解决这个问题。 当我尝试使用post请求发送数据时,会发生404错误。
routes / img.js - 更新
var ImageFile = require('../models/imageFiles');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'img/') // Set directory
},
filename: function (req, file, cb) {
cb(null, file.name) // Set file name
}
});
var img = multer({ storage: storage });
router.post('/upload', img.single('imgfile'), (req, res, next) => {
var imageFile = new ImageFile({
name: req.body.name,
type: req.body.type,
size: req.body.size,
content: req.body.content
});
imageFile.save((err, result) => {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
res.status(201).json({
message: 'User created',
obj: result
});
});
});
module.exports = router;
app.js
const express = require('express');
var bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var appRoutes = require('./routes/app');
var userRoutes = require('./routes/user');
var imgRoutes = require('./routes/img');
var app = express();
// Start
app.use(express.static(path.join(__dirname, '../awesome-drill/dist')));
app.use(logger('dev'));
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-Width, Content-Type, Accept');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
next();
});
app.use('/user', userRoutes);
app.use('/img', imgRoutes);
app.use('/', appRoutes);
app.use(express.static('routes'));
// It's for routing SPA
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../awesome-drill/dist/index.html'));
});
app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
前端服务(angular4)
import { Injectable } from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
@Injectable()
export class FileService {
public userId = localStorage.getItem('userId');
constructor(private http: Http) { }
imgUpload(obj) {
const body = JSON.stringify(obj);
const headers = new Headers({
'Content-Type': 'application/json'
});
return this.http.post('img/upload', body, {
headers: headers
})
.map((response: Response) => response.json());
}
}
感谢你,我发现了我的错误并添加了它。但是,仍然会出现404错误。
答案 0 :(得分:0)
您没有导出路由器。将以下内容添加到routes/img.js
文件的末尾。
module.exports = router;
现在的方式,没有默认导出,所以当你require('./routes/img')
进行任何操作时。如果你console.log(imgRoutes)
app.js
undefined
,它可能会返回{{1}}。