将本地文件从React发布到Express结果中,出现404错误

问题描述 投票:0回答:1

我在客户端文件夹中有一个React应用程序,在根文件夹中有一个Express服务器。 React应用程序具有一个选择文件按钮和一个提交按钮。我希望该文件被React应用程序捕获并移动到我的React应用程序的public / uploads文件夹中。

我是新手,我肯定我缺少一些简单的东西,但是无论我尝试什么,Express服务器中的post方法都不会执行。我只是遇到404错误。

这是我的Express服务器:

var express = require('express');
var fileUpload = require('express-fileupload');
var app = express();

app.use(fileUpload());
//upload endpoint

app.post('/uploads', (req, res) => {
  console.log("this is the post");
  if (req.files === null) {
    return res.status(400).json({ msg: 'No file Uploaded' });
  }

  const file = req.files.file;
  file.mv(`${__dirname}/client/public/uploads${file.name}`, err => {
    if (err) {
      console.error(err);
      return res.status(500).send(err);
    }
    res.json({ fileName: file.name, filePath: `/${file.name}` });
  })
})

app.listen(5000, () => console.log('Express server started on port 5000...'));

这是我的React组件:

import React, { Fragment, useState } from 'react';
import axios from 'axios';

const AddNewItem = () => {
  const [file, setFile] = useState('');
  const [fileName, setFileName] = useState('Choose File');
  const [uploadedFile, setUploadedFile] = useState({});

  const onChange = e => {
    setFile(e.target.files[0]);
    setFileName(e.target.files[0].name);
  }

  const onSubmit = async e => {
    e.preventDefault();

    const formData = new FormData();
    formData.append('file', file)

    try {
      console.log("Uploading")
      const res = await axios.post('http://localhost:3000/uploads', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log("Uploading")
      const { fileName, filePath } = res.data;
      setUploadedFile({ fileName, filePath })

    } catch (err) {
      if (err.response.data.msg === 500) {
        console.log("There was a problem with the server.");
      }
      else {
        console.log(err);
        console.log(err.response.data.msg);
      }
    }
  }

  return (
    <Fragment>
      <form onSubmit={onSubmit}>
        <label>Title:</label><br />
        <input type="text" id="title" name="title" /><br />
        <label>Image:</label><br />
        <input type="file" id="image" name="image" onChange={onChange}></input>
        <button type="submit">Submit</button>
      </form>
    </Fragment>
  );
}

export default AddNewItem;

我的React package.json具有定义的代理:

{
  "name": "react-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "axios": "^0.19.2",
    "bootstrap": "^4.5.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-paypal-express-checkout": "^1.0.5",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.1",
    "styled-components": "^5.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "proxy": "http://localhost:5000",
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

这是Express的package.json:

{
  "name": "store",
  "main": "server.js",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node server.js",
    "server": "nodemon server.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\""
  },
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "cookie-parser": "^1.4.5",
    "cors": "^2.8.5",
    "debug": "^2.6.9",
    "express": "^4.17.1",
    "express-fileupload": "^1.1.7-alpha.3",
    "http-errors": "^1.6.3",
    "jade": "^1.11.0",
    "morgan": "^1.9.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "devDependencies": {
    "concurrently": "^5.2.0",
    "nodemon": "^2.0.4"
  }
}

我在这里关注教程https://www.youtube.com/watch?v=b6Oe2puTdMQ&t=1709s

我已经尝试在react应用程序和express中将路径更改为简单/。我尝试指定完整的本地主机URL。没用。另一个有趣的事情是,我最终进入了onSubmit catch块,并且err.response.data.msg是未定义的。对我来说,这似乎没有得到Express的任何答复。

以下是提交结果的屏幕截图:enter image description here

我想念什么?

javascript node.js reactjs express post
1个回答
0
投票

确定,您是快递服务器正在端口5000上运行

您正在通过端口3000调用api

app.listen(5000, () => console.log('Express server started on port 5000...'));


await axios.post('http://localhost:3000/uploads', formData,
© www.soinside.com 2019 - 2024. All rights reserved.