我正在尝试将图像从我的前端上传到 mongodb 数据库。POSTMAN 一切正常,但每当我尝试从前端上传图像时,我的控制台日志中都会出现错误的端口错误。(我正在尝试将图像上传到端口号 3002,但在端口显示在 9000 的位置出现 API 路由错误。我的前端在端口 9000 上运行,后端在 3002 上运行。
这是我尝试上传图像的文件。
import { Avatar, Input } from '@material-ui/core'
import { SettingsInputAntenna } from '@material-ui/icons'
import axios from 'axios'
import React, { useState } from 'react'
import { useStateValue } from '../StateProvider'
import './MessageSender.css'
import FormData from 'form-data'
const MessageSender = () => {
const [input,setInput]=useState('')
const [imageUrl,setImageUrl]=useState('')
const [image,setImage]=useState(null)
const [{user},dispatch]=useStateValue()
const handleChange=(e)=>{
if(e.target.files[0]){
setImage(e.target.files[0]);
}
}
const handleSubmit=async(e)=>{
e.preventDefault()
if(image){
const imgForm=new FormData()
imgForm.append('file',image,image.name)
axios.post('/upload/image',imgForm,{
headers:{
'accept':'application/json',
'Accept-language':'en-US,en;q=0.8',
'Content-Type':`multipart/form-data; boundary=${imgForm._boundary}`,
}
}).then((res)=>{
console.log(res.data)
const postData={
text: input,
imgName: res.data.filename,
user:user.displayName,
avatar:user.photoURL,
timestamp: Date.now()
}
console.log(postData)
savePost(postData)
}).catch(err=>{
console.log(err);
})
}
else{
const postData ={
text: input,
user: user.displayName,
avatar : user.photoURL,
timestamp: Date.now()
}
console.log(postData)
savePost(postData)
}
setImageUrl('')
setInput('')
setImage(null)
}
const savePost=async(postData)=>{
await axios.post('/upload/post',postData)
.then((res)=>{
console.log(res)
})
}
return (
<div className='messageSender'>
<div className='messageSender_top'>
<div className="avatar_post_class">
<Avatar src={user.photoURL}/>
</div>
<form>
<div className="post_text">
<input type="text" className='messegeSender_input' placeholder="Whats`s up with you ?" value={input} onChange = {(e)=>setInput(e.target.value)}/>
</div>
<div className="file_selection">
<input type="file" id="fileselectionid" className='messeageSender_fileSelector' onChange= {handleChange}/>
</div>
<div className="post_button">
<button onClick={handleSubmit} type='Submit' id="postbutton"> Post </button>
</div>
</form>
</div>
</div>
)
}
export default MessageSender
axios.js
import axios from 'axios'
const instance=axios.create({
baseURL: 'http://localhost:3002'
})
export default instance
axios.get('http://localhost:3002/upload/image')