簡體   English   中英

MERN 使用 multer 上傳文件

[英]MERN Upload file with multer

我正在制作一個 pinterest 克隆所以我需要上傳圖像但我無法從前端到后端獲取文件(使用 axios)這是服務器

我測試了很多東西,但我不明白缺陷在哪里。 該應用程序存儲照片,似乎問題發生在我想將數據獲取到后端但只有文件因為我可以從前端獲取字符串

const express = require('express');
const app = express()
const mongoose = require('mongoose')
const cors = require('cors')
const Photo = require('./models/Photo')
const multer = require('multer')
//MiddleWare
app.use(cors())
app.use(express.json())

mongoose.connect('', () =>{
    console.log('Connected to DB..')
})

// storage 
const Storage = multer.diskStorage({
  destination: 'uploads',
  filename: (req, file,cb) =>{
    cb(null, file.originalname)
  }
})

const upload = multer({
  storage: Storage,
}).single('testImage')

app.post('/add', async(req, res) =>{


  console.log(req.files)
})

app.listen(3001, () =>{
    console.log('Listening..')
})

這是客戶端

/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable react/jsx-no-comment-textnodes */
import React, { useState, useRef } from "react";
import NotificationsIcon from "@mui/icons-material/Notifications";
import AddAPhotoIcon from "@mui/icons-material/AddAPhoto";
import "./Header.css";
import axios from "axios"
const Header = ({gallery, setGallery}) => {
  const [open, setOpen] = useState(false);
const [photo, setPhoto] = useState('')
  const handleModel = (e) => {
    setOpen(!open);
  };
  const handlePhoto = (e) => {
    setPhoto(e.target.files[0])
  
}
const handleSubmit = e=>{
  e.preventDefault();
  setOpen(!open);

console.log(photo)
  axios.post('http://localhost:3001/add',{photo: photo})
  .then(res => {
     console.log(res);
  })
  .catch(err => {
     console.log(err);
  });
}
  return (
    <div className="header">
      <div className="nav">
        <img
          src="https://i.pinimg.com/originals/0d/ea/4a/0dea4ad3030467e2f65cde00935ba62b.png"
          className="logo"
        />

        <input type="text" className="search-input" placeholder="Search" />
        <NotificationsIcon color="action" fontSize="large" className="icon" />
        <AddAPhotoIcon
          color="action"
          fontSize="large"
          className="add-icon icon"
          onClick={handleModel}
        />
      </div>
      {open ? (
        <form  onSubmit={handleSubmit} className="popup" encType='multipart/form-data'>
          <input
            type="file"
            accept=".png, .jpg, .jpeg"
            filename='testImage'
            onChange={handlePhoto}

          />
          <button >Submit</button>
        </form>
      ) : (
        ""
      )}
    </div>
  );
};

export default Header;

當我上傳圖像時,服務器控制台記錄未定義,但為什么?

... console.log(req) 的 output


Listening..
<ref *2> IncomingMessage {
  _readableState: ReadableState {
    objectMode: false,
    highWaterMark: 16384,      
    buffer: BufferList { head: 
null, tail: null, length: 0 }, 
    length: 0,
    pipes: [],
    flowing: true,
    ended: true,
    endEmitted: true,
    reading: false,
    constructed: true,
    sync: false,
    needReadable: false,       
    emittedReadable: false,    
    readableListening: false,  
    resumeScheduled: false,    
    errorEmitted: false,       
    emitClose: true,
    autoDestroy: true,
    destroyed: false,
    errored: null,
    closed: false,
    closeEmitted: false,       
    defaultEncoding: 'utf8',   
    awaitDrainWriters: null,   
    multiAwaitDrain: false,    
    readingMore: false,        
    dataEmitted: true,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: false   
  },
  _events: [Object: null prototype] { end: [Function: clearRequestTimeout] },
  _eventsCount: 1,
  _maxListeners: undefined,    
  socket: <ref *1> Socket {    
    connecting: false,
    _hadError: false,
    _parent: null,
    _host: null,
    _readableState: ReadableState {
      objectMode: false,       
      highWaterMark: 16384,    
      buffer: BufferList { head: null, tail: null, length: 0 },
      length: 0,
      pipes: [],
      flowing: true,
      ended: false,
      endEmitted: false,       
      reading: true,
      constructed: true,       
      sync: false,
      needReadable: true,      
      emittedReadable: false,  
      readableListening: false,      resumeScheduled: false,  
      errorEmitted: false,     
      emitClose: false,        
      autoDestroy: true,       
      destroyed: false,        
      errored: null,
      closed: false,
      closeEmitted: false,     
      defaultEncoding: 'utf8', 
      awaitDrainWriters: null, 
      multiAwaitDrain: false,  
      readingMore: false,      
      dataEmitted: false,      
      decoder: null,
      encoding: null,
      [Symbol(kPaused)]: false 
    },
    _events: [Object: null prototype] {
      end: [Array],
      timeout: [Function: socketOnTimeout],
      data: [Function: bound socketOnData],
      error: [Function: socketOnError],
      close: [Array],
      drain: [Function: bound socketOnDrain],
      resume: [Function: onSocketResume],
      pause: [Function: onSocketPause]
    },
    _eventsCount: 8,
    _maxListeners: undefined,  
    _writableState: WritableState {
      objectMode: false,       
      highWaterMark: 16384,    
      finalCalled: false,      
      needDrain: false,        
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,        
      decodeStrings: false,    
      defaultEncoding: 'utf8', 
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false, 
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,      buffered: [],
      bufferedIndex: 0,        
      allBuffers: true,        
      allNoop: true,
      pendingcb: 0,
      constructed: true,       
      prefinished: false,      
      errorEmitted: false,     
      emitClose: false,        
      autoDestroy: true,       
      errored: null,
      closed: false,
      closeEmitted: false,     
      [Symbol(kOnFinished)]: []    },
    allowHalfOpen: true,       
    _sockname: null,
    _pendingData: null,        
    _pendingEncoding: '',      
    server: Server {
      maxHeaderSize: undefined,      insecureHTTPParser: undefined,
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,      _connections: 1,
      _handle: [TCP],
      _usingWorkers: false,    
      _workers: [],
      _unref: false,
      allowHalfOpen: true,     
      pauseOnConnect: false,   
      httpAllowHalfOpen: false,      timeout: 0,
      keepAliveTimeout: 5000,  
      maxHeadersCount: null,   
      maxRequestsPerSocket: 0, 
      headersTimeout: 60000,   
      requestTimeout: 0,       
      _connectionKey: '6::::3001',
      [Symbol(IncomingMessage)]: [Function: IncomingMessage], 
      [Symbol(ServerResponse)]: [Function: ServerResponse],   
      [Symbol(kCapture)]: false,
      [Symbol(async_id_symbol)]: 9
    },
    _server: Server {
      maxHeaderSize: undefined,      insecureHTTPParser: undefined,
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,      _connections: 1,
      _handle: [TCP],
      _usingWorkers: false,    
      _workers: [],
      _unref: false,
      allowHalfOpen: true,     
      pauseOnConnect: false,   
      httpAllowHalfOpen: false,      timeout: 0,
      keepAliveTimeout: 5000,  
      maxHeadersCount: null,   
      maxRequestsPerSocket: 0, 
      headersTimeout: 60000,   
      requestTimeout: 0,       
      _connectionKey: '6::::3001',
      [Symbol(IncomingMessage)]: [Function: IncomingMessage], 
      [Symbol(ServerResponse)]: [Function: ServerResponse],   
      [Symbol(kCapture)]: false,
      [Symbol(async_id_symbol)]: 9
    },
    parser: HTTPParser {       
      '0': [Function: bound setRequestTimeout],
      '1': [Function: parserOnHeaders],
      '2': [Function: parserOnHeadersComplete],
      '3': [Function: parserOnBody],
      '4': [Function: parserOnMessageComplete],
      '5': [Function: bound onParserExecute],
      '6': [Function: bound onParserTimeout],
      _headers: [],
      _url: '',
      socket: [Circular *1],   
      incoming: [Circular *2], 
      outgoing: null,
      maxHeaderPairs: 2000,    
      _consumed: true,
      onIncoming: [Function: bound parserOnIncoming],
      [Symbol(owner_symbol)]: [HTTPServerAsyncResource]       
    },
    on: [Function: socketListenerWrap],
    addListener: [Function: socketListenerWrap],
    prependListener: [Function: socketListenerWrap],
    setEncoding: [Function: socketSetEncoding],
    _paused: false,
    _httpMessage: ServerResponse {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,        
      _last: false,
      chunkedEncoding: false,  
      shouldKeepAlive: true,   
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true, 
      useChunkedEncodingByDefault: true,
      sendDate: true,
      _removedConnection: false,
      _removedContLen: false,  
      _removedTE: false,       
      _contentLength: null,    
      _hasBody: true,
      _trailer: '',
      finished: false,
      _headerSent: false,      
      _closed: false,
      socket: [Circular *1],   
      _header: null,
      _keepAliveTimeout: 5000, 
      _onPendingData: [Function: bound updateOutgoingData],   
      req: [Circular *2],      
      _sent100: false,
      _expect_continue: false, 
      locals: [Object: null prototype] {},
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,     
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    [Symbol(async_id_symbol)]: 
35,
    [Symbol(kHandle)]: TCP {   
      reading: true,
      onconnection: null,      
      _consumed: true,
      [Symbol(owner_symbol)]: [Circular *1]
    },
    [Symbol(kSetNoDelay)]: false,
    [Symbol(lastWriteQueueSize)]: 0,
    [Symbol(timeout)]: null,   
    [Symbol(kBuffer)]: null,   
    [Symbol(kBufferCb)]: null, 
    [Symbol(kBufferGen)]: null,    [Symbol(kCapture)]: false, 
    [Symbol(kBytesRead)]: 0,   
    [Symbol(kBytesWritten)]: 0,    [Symbol(RequestTimeout)]: undefined
  },
  httpVersionMajor: 1,
  httpVersionMinor: 1,
  httpVersion: '1.1',
  complete: true,
  rawHeaders: [
    'Host',
    'localhost:3001',
    'Connection',
    'keep-alive',
    'Content-Length',
    '12',
    'sec-ch-ua',
    '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    'Accept',
    'application/json, text/plain, */*',
    'Content-Type',
    'application/json',        
    'sec-ch-ua-mobile',        
    '?1',
    'User-Agent',
    'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Mobile Safari/537.36',
    'sec-ch-ua-platform',      
    '"Android"',
    'Origin',
    'http://localhost:3000',   
    'Sec-Fetch-Site',
    'same-site',
    'Sec-Fetch-Mode',
    'cors',
    'Sec-Fetch-Dest',
    'empty',
    'Referer',
    'http://localhost:3000/',  
    'Accept-Encoding',
    'gzip, deflate, br',       
    'Accept-Language',
    'en-US,en;q=0.9,ru-RU;q=0.8,ru;q=0.7'
  ],
  rawTrailers: [],
  aborted: false,
  upgrade: false,
  url: '/add',
  method: 'POST',
  statusCode: null,
  statusMessage: null,
  client: <ref *1> Socket {    
    connecting: false,
    _hadError: false,
    _parent: null,
    _host: null,
    _readableState: ReadableState {
      objectMode: false,       
      highWaterMark: 16384,    
      buffer: BufferList { head: null, tail: null, length: 0 },
      length: 0,
      pipes: [],
      flowing: true,
      ended: false,
      endEmitted: false,       
      reading: true,
      constructed: true,       
      sync: false,
      needReadable: true,      
      emittedReadable: false,  
      readableListening: false,      resumeScheduled: false,  
      errorEmitted: false,     
      emitClose: false,        
      autoDestroy: true,       
      destroyed: false,        
      errored: null,
      closed: false,
      closeEmitted: false,     
      defaultEncoding: 'utf8', 
      awaitDrainWriters: null, 
      multiAwaitDrain: false,  
      readingMore: false,      
      dataEmitted: false,      
      decoder: null,
      encoding: null,
      [Symbol(kPaused)]: false 
    },
    _events: [Object: null prototype] {
      end: [Array],
      timeout: [Function: socketOnTimeout],
      data: [Function: bound socketOnData],
      error: [Function: socketOnError],
      close: [Array],
      drain: [Function: bound socketOnDrain],
      resume: [Function: onSocketResume],
      pause: [Function: onSocketPause]
    },
    _eventsCount: 8,
    _maxListeners: undefined,  
    _writableState: WritableState {
      objectMode: false,       
      highWaterMark: 16384,    
      finalCalled: false,      
      needDrain: false,        
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,        
      decodeStrings: false,    
      defaultEncoding: 'utf8', 
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false, 
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,      buffered: [],
      bufferedIndex: 0,        
      allBuffers: true,        
      allNoop: true,
      pendingcb: 0,
      constructed: true,       
      prefinished: false,      
      errorEmitted: false,     
      emitClose: false,        
      autoDestroy: true,       
      errored: null,
      closed: false,
      closeEmitted: false,     
      [Symbol(kOnFinished)]: []    },
    allowHalfOpen: true,       
    _sockname: null,
    _pendingData: null,        
    _pendingEncoding: '',      
    server: Server {
      maxHeaderSize: undefined,      insecureHTTPParser: undefined,
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,      _connections: 1,
      _handle: [TCP],
      _usingWorkers: false,    
      _workers: [],
      _unref: false,
      allowHalfOpen: true,     
      pauseOnConnect: false,   
      httpAllowHalfOpen: false,      timeout: 0,
      keepAliveTimeout: 5000,  
      maxHeadersCount: null,   
      maxRequestsPerSocket: 0, 
      headersTimeout: 60000,   
      requestTimeout: 0,       
      _connectionKey: '6::::3001',
      [Symbol(IncomingMessage)]: [Function: IncomingMessage], 
      [Symbol(ServerResponse)]: [Function: ServerResponse],   
      [Symbol(kCapture)]: false,
      [Symbol(async_id_symbol)]: 9
    },
    _server: Server {
      maxHeaderSize: undefined,      insecureHTTPParser: undefined,
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,      _connections: 1,
      _handle: [TCP],
      _usingWorkers: false,    
      _workers: [],
      _unref: false,
      allowHalfOpen: true,     
      pauseOnConnect: false,   
      httpAllowHalfOpen: false,      timeout: 0,
      keepAliveTimeout: 5000,  
      maxHeadersCount: null,   
      maxRequestsPerSocket: 0, 
      headersTimeout: 60000,   
      requestTimeout: 0,       
      _connectionKey: '6::::3001',
      [Symbol(IncomingMessage)]: [Function: IncomingMessage], 
      [Symbol(ServerResponse)]: [Function: ServerResponse],   
      [Symbol(kCapture)]: false,
      [Symbol(async_id_symbol)]: 9
    },
    parser: HTTPParser {       
      '0': [Function: bound setRequestTimeout],
      '1': [Function: parserOnHeaders],
      '2': [Function: parserOnHeadersComplete],
      '3': [Function: parserOnBody],
      '4': [Function: parserOnMessageComplete],
      '5': [Function: bound onParserExecute],
      '6': [Function: bound onParserTimeout],
      _headers: [],
      _url: '',
      socket: [Circular *1],   
      incoming: [Circular *2], 
      outgoing: null,
      maxHeaderPairs: 2000,    
      _consumed: true,
      onIncoming: [Function: bound parserOnIncoming],
      [Symbol(owner_symbol)]: [HTTPServerAsyncResource]       
    },
    on: [Function: socketListenerWrap],
    addListener: [Function: socketListenerWrap],
    prependListener: [Function: socketListenerWrap],
    setEncoding: [Function: socketSetEncoding],
    _paused: false,
    _httpMessage: ServerResponse {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,        
      _last: false,
      chunkedEncoding: false,  
      shouldKeepAlive: true,   
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true, 
      useChunkedEncodingByDefault: true,
      sendDate: true,
      _removedConnection: false,
      _removedContLen: false,  
      _removedTE: false,       
      _contentLength: null,    
      _hasBody: true,
      _trailer: '',
      finished: false,
      _headerSent: false,      
      _closed: false,
      socket: [Circular *1],   
      _header: null,
      _keepAliveTimeout: 5000, 
      _onPendingData: [Function: bound updateOutgoingData],   
      req: [Circular *2],      
      _sent100: false,
      _expect_continue: false, 
      locals: [Object: null prototype] {},
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,     
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    [Symbol(async_id_symbol)]: 
35,
    [Symbol(kHandle)]: TCP {   
      reading: true,
      onconnection: null,      
      _consumed: true,
      [Symbol(owner_symbol)]: [Circular *1]
    },
    [Symbol(kSetNoDelay)]: false,
    [Symbol(lastWriteQueueSize)]: 0,
    [Symbol(timeout)]: null,   
    [Symbol(kBuffer)]: null,   
    [Symbol(kBufferCb)]: null, 
    [Symbol(kBufferGen)]: null,    [Symbol(kCapture)]: false, 
    [Symbol(kBytesRead)]: 0,   
    [Symbol(kBytesWritten)]: 0,    [Symbol(RequestTimeout)]: undefined
  },
  _consuming: true,
  _dumped: false,
  next: [Function: next],      
  baseUrl: '',
  originalUrl: '/add',
  _parsedUrl: Url {
    protocol: null,
    slashes: null,
    auth: null,
    host: null,
    port: null,
    hostname: null,
    hash: null,
    search: null,
    query: null,
    pathname: '/add',
    path: '/add',
    href: '/add',
    _raw: '/add'
  },
  params: {},
  query: {},
  res: <ref *3> ServerResponse 
{
    _events: [Object: null prototype] { finish: [Function: bound resOnFinish] },
    _eventsCount: 1,
    _maxListeners: undefined,  
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: false,
    _last: false,
    chunkedEncoding: false,    
    shouldKeepAlive: true,     
    maxRequestsOnConnectionReached: false,
    _defaultKeepAlive: true,   
    useChunkedEncodingByDefault: true,
    sendDate: true,
    _removedConnection: false, 
    _removedContLen: false,    
    _removedTE: false,
    _contentLength: null,      
    _hasBody: true,
    _trailer: '',
    finished: false,
    _headerSent: false,        
    _closed: false,
    socket: <ref *1> Socket {  
      connecting: false,       
      _hadError: false,        
      _parent: null,
      _host: null,
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 8,
      _maxListeners: undefined,      _writableState: [WritableState],
      allowHalfOpen: true,     
      _sockname: null,
      _pendingData: null,      
      _pendingEncoding: '',    
      server: [Server],        
      _server: [Server],       
      parser: [HTTPParser],    
      on: [Function: socketListenerWrap],
      addListener: [Function: socketListenerWrap],
      prependListener: [Function: socketListenerWrap],        
      setEncoding: [Function: socketSetEncoding],
      _paused: false,
      _httpMessage: [Circular *3],
      [Symbol(async_id_symbol)]: 35,
      [Symbol(kHandle)]: [TCP],      [Symbol(kSetNoDelay)]: false,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null, 
      [Symbol(kBuffer)]: null, 
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0, 
      [Symbol(kBytesWritten)]: 
0,
      [Symbol(RequestTimeout)]: undefined
    },
    _header: null,
    _keepAliveTimeout: 5000,   
    _onPendingData: [Function: 
bound updateOutgoingData],     
    req: [Circular *2],        
    _sent100: false,
    _expect_continue: false,   
    locals: [Object: null prototype] {},
    [Symbol(kCapture)]: false, 
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,       
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      'x-powered-by': [Array], 
      'access-control-allow-origin': [Array]
    }
  },
  body: { photo: {} },
  _body: true,
  length: undefined,
  route: Route {
    path: '/add',
    stack: [ [Layer], [Layer] ],
    methods: { post: true }    
  },
  [Symbol(kCapture)]: false,   
  [Symbol(kHeaders)]: {        
    host: 'localhost:3001',    
    connection: 'keep-alive',  
    'content-length': '12',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
    accept: 'application/json, 
text/plain, */*',
    'content-type': 'application/json',
    'sec-ch-ua-mobile': '?1',  
    'user-agent': 'Mozilla/5.0 
(Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/98.0.4758.102 Mobile Safari/537.36',
    'sec-ch-ua-platform': '"Android"',
    origin: 'http://localhost:3000',
    'sec-fetch-site': 'same-site',
    'sec-fetch-mode': 'cors',  
    'sec-fetch-dest': 'empty', 
    referer: 'http://localhost:3000/',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9,ru-RU;q=0.8,ru;q=0.7'  
  },
  [Symbol(kHeadersCount)]: 32, 
  [Symbol(kTrailers)]: null,   
  [Symbol(kTrailersCount)]: 0, 
  [Symbol(RequestTimeout)]: undefined
}
Connected to DB..

您是否嘗試記錄req的值?

app.post('/add', async(req, res) =>{
  console.log(req)
})

你正在做axios.post('http://localhost:3001/add',{photo: photo}) 根據簽名,第二個密鑰應該是數據: axios.post(url[, data[, config]])

要使用 POST 發送文件,您需要發送FormData的實例。

const bodyFormData = new FormData();
bodyFormData.append("media", file);
axios.post('http://localhost:3001/add',{file: bodyFormData})

在服務器中嘗試根據req的值訪問正確的密鑰。 req.files

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM