如何解决无法从后端nodejs将图像显示到reactjs上的卡组件上
我试图显示来自后端(使用nodejs的后端,序列化)上传的图像,并且我尝试将其显示到后端上的卡组件(即使用reactjs作为前端),我将图像输入并保存到了文件夹名称public / img,尝试通过邮递员上传时,图像已成功输入文件,此处为结果 enter image description here
错误是 GET http:// localhost:3000 / img / 92c4c0be36fa5f1419f938f509df5472.png 404(未找到)
import React,{Component} from 'react';
import {Card,CardGroup} from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import jwt_decode from 'jwt-decode';
class ProdukList extends Component{
constructor(props){
super(props);
this.state = {
items:[],isLoaded: false
}
}
componentDidMount(){
const token = localStorage.getItem('usertoken')
const decoded = jwt_decode(token)
this.setState({
id_user: decoded.id_user,})
console.log(decoded.id_user)
fetch(`http://localhost:4000/product/?id_user=${decoded.id_user}`)
.then(res=> res.json())
.then(
(result)=>{
this.setState({
items: result,isLoaded: true
});
console.log(result)
},(error) =>{
this.setState((error));
console.log(error)
}
)
}
render(){
console.log(this.state.items)
var{isLoaded,items}=this.state;
if(!isLoaded){
return<div>Loading.......</div>
}else{
return(
<div className="ProdukList">
{items && items.length > 0 ? items.map(item =>(
<CardGroup>
<Card style={{width: '18rem'}} key={item.id_produk}>
<Card.Img variant="top" src={item.image} alt="img"></Card.Img>
<Card.Body>
<Card.Title>
{item.Nama_produk}
</Card.Title>
<Card.Text>
{item.Price}<br/>
{item.Deskripsi}
</Card.Text>
<Card.Footer>
<small className="text-muted">Stock : {item.Jumlah_stock}</small>
</Card.Footer>
</Card.Body>
</Card>
</CardGroup>
)) : 'Kosong'}
{console.log(items)}
</div>
)
}
}
}
export default ProdukList;
这里是数据库模型
const Sequelize = require("sequelize")
const db = require("../database/db")
//const {uploadDir} = require("../upload")
const multer = require("multer");
const express = require("express")
const app = express();
const path = require('path');
const crypto = require('crypto');
app.use(express.static('public/img'));
const uploadDir = '/img/';
const storage = multer.diskStorage({
destination:"./public"+uploadDir,filename: function (req,file,cb){
crypto.pseudoRandomBytes(16,function(err,raw){
if (err) return cb (err)
cb(null,raw.toString('hex')+path.extname(file.originalname))
})
}
})
const uploadfile = multer({storage: storage,dest:uploadDir})
module.exports= uploadfile;
module.exports = db.sequelize.define(
'produks',{
id_produk:{
type: Sequelize.INTEGER,primaryKey: true,autoIncrement: true
},id_user: {
type: Sequelize.INTEGER
},Nama_toko:{
type: Sequelize.STRING
},Nama_Produk:{
type: Sequelize.INTEGER
},image:{
type: Sequelize.STRING,get(){
const image = this.getDataValue('image');
return uploadDir+image;
}
},Deskripsi:{
type: Sequelize.STRING
},Price:{
type: Sequelize.INTEGER
},Jumlah_stock:{
type:Sequelize.INTEGER
}
},{
timestamps: false
}
)
const express=require("express")
const product = express.Router()
// const multer = require("multer");
const uploadfile = require('../upload')
const produk = require('../models/produk')
const {validationResult } = require('express-validator/check');
const { matchedData,sanitize } = require('express-validator/filter'); //sanitize form params
produk.sync().then(()=>{
console.log("produk berhasil sync")
}).catch(err=>{
console.log("produk gagal sync",err)
})
product.post('/addproduk/',[
uploadfile.single('image')
],(req,res)=>{
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(422).json({errors: errors.mapped()})
}
const produkData = {
id_user:req.body.id_user,Nama_toko:req.body.Nama_toko,Nama_Produk:req.body.Nama_Produk,image: req.file === undefined ? "": req.file.filename,Deskripsi:req.body.Deskripsi,Price:req.body.Price,Jumlah_stock:req.body.Jumlah_stock
}
console.log(produkData)
if(!produkData){
res.status(400)
res.json({
error: 'Bad data'
})
}else{
produk.create(produkData)
.then(data=>{
res.send(data)
})
.catch(err=>{
res.json('error: '+err)
})
}
})
解决方法
您的react项目具有相同的“ / public”文件夹吗?当您启动自己的React项目进行开发时,它会在端口3000上启动自己的“服务器”,您需要在React和Express项目之间共享“ public”文件夹
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。