У меня проблема при попытке загрузить файл с помощью пост-запроса, получая ошибку:
POST http://localhost: 8080 / api / files 404 (Не нашел).
URL страницы, с которой я пытаюсь загрузить файл: http://localhost:8080/playlist/f9aeb4fd-f6c3-46a2-b269-20ae8508e612
, но когда я пытаюсь изменить мой POST
запрос на http://localhost:8080/playlist/f9aeb4fd-f6c3-46a2-b269-20ae8508e612/api/files
, изменив app.use('/api', require('./file'))
на app.use('/playlist/f9aeb4fd-f6c3-46a2-b269-20ae8508e612/api'
, require('./file'))
Я все еще получаю ту же ошибку.
сервер. js
import { MongoClient } from 'mongodb';
import path from 'path';
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import './initialize-db';
import { authenticationRoute } from './authenticate';
let port = process.env.PORT || 7777;
let app = express();
app.use(
cors(),
bodyParser.urlencoded({extended:true}),
bodyParser.json()
);
let server = app.listen(port,console.info("Server running, listening on port ", port));
authenticationRoute(app);
if (process.env.NODE_ENV == `production`) {
app.use(express.static(path.resolve(__dirname,'../../dist')));
app.get('/*',(req,res)=>{
res.sendFile(path.resolve('index.html'));
});
}
mongoose.connect(myMongoUrl);
app.use(function(req, res, next) { //allow cross origin requests
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", true);
next();
});
app.use('/api', require('./file'));
module.exports = server;
файл. js
const router = require('express').Router();
import multer from 'multer';
import {mongo, connection} from 'mongoose';
import Grid from 'gridfs-stream';
Grid.mongo = mongo;
let gfs = Grid(myMongoUrl);
// set up connection to db for file storage
const storage = require('multer-gridfs-storage')({
db: connection.db,
file: (req, file) => {
return {
filename: file.originalname
}
}
});
// sets file input to single file
const singleUpload = multer({ storage: storage }).single('file');
router.get('/files/:filename', (req, res) => {
gfs.files.find({ filename: req.params.filename }).toArray((err, files) => {
if(!files || files.length === 0){
return res.status(404).json({
message: "Could not find file"
});
}
let readstream = gfs.createReadStream({
filename: files[0].filename
})
res.set('Content-Type', files[0].contentType);
return readstream.pipe(res);
});
});
router.get('/files', (req, res) => {
gfs.files.find().toArray((err, files) => {
if(!files || files.length === 0){
return res.status(404).json({
message: "Could not find files"
});
}
return res.json(files);
});
});
router.post('/files', singleUpload, (req, res) => {
if (req.file) {
return res.json({
success: true,
file: req.file
});
}
res.send({ success: false });
});
router.delete('/files/:id', (req, res) => {
gfs.remove({ _id: req.params.id }, (err) => {
if (err) return res.status(500).json({ success: false })
return res.json({ success: true });
})
})
module.exports = router;
TaskDetail.jsx
import React, { Component } from 'react';
import { connect } from 'react-redux';
class TaskDetail extends Component {
constructor(props) {
super(props);
this.state = {
files: [],
file: ''
}
this.loadFiles = this.loadFiles.bind(this);
}
componentDidMount() {
this.loadFiles();
}
loadFiles() {
fetch('/api/files')
.then(res => res.json())
.then(files => {
if (files.message) {
console.log('No Files');
this.setState({ files: [] })
} else {
this.setState({ files })
}
});
}
fileChanged(event) {
const f = event.target.files[0];
this.setState({
file: f
});
}
deleteFile(event) {
event.preventDefault();
const id = event.target.id;
fetch('/api/files/'+id, {
method: 'DELETE'
}).then(res => res.json())
.then(response => {
console.log(response);
if (response.success) this.loadFiles()
else alert('Delete Failed');
})
}
uploadFile(event) {
event.preventDefault();
let data = new FormData();
data.append('file', this.state.file);
fetch('/api/files', {
method: 'POST',
body: data
}).then(res => res.json())
.then(data => {
if (data.success) {
this.loadFiles();
} else {
alert('Upload failed');
}
});
}
render() {
const { files } = this.state;
return(
<div className="card p-3 col-6">
<input type="file" onChange={this.fileChanged.bind(this)}/>
<button onClick={this.uploadFile.bind(this)}>Upload</button>
<table className="App-table">
<thead>
<tr>
<th>File</th>
<th>Uploaded</th>
<th>Size</th>
<th></th>
</tr>
</thead>
<tbody>
{files.map((file, index) => {
var d = new Date(file.uploadDate);
return (
<tr key={index}>
<td><a href={`http://localhost:8080/api/files/${file.filename}`}>{file.filename}</a></td>
<td>{`${d.toLocaleDateString()} ${d.toLocaleTimeString()}`}</td>
<td>{(Math.round(file.length/100) / 10)+'KB'}</td>
<td><button onClick={this.deleteFile.bind(this)} id={file._id}>Remove</button></td>
</tr>
)
})}
</tbody>
</table>
</div>
)
}
}
function mapStateToProps(state,ownProps){
let id = ownProps.match.params.id;
let task = state.tasks.find(task=>task.id === id);
let isOwner = state.session.id === task.owner;
let groups = state.groups;
return {
id,
task,
isOwner,
sessionID: state.session.id,
groups
}
}
function mapDispatchToProps(dispatch, ownProps){
let id = ownProps.match.params.id;
return {
setTaskCompletion(id,isComplete){
dispatch(setTaskCompletion(id,isComplete));
},
setTaskGroup(e){
dispatch(setTaskGroup(id,e.target.value));
},
setTaskName(e){
dispatch(setTaskName(id,e.target.value));
}
}
}
export const ConnectedTaskDetail = connect(mapStateToProps,mapDispatchToProps)(TaskDetail);