简体   繁体   中英

How to resolve 404 error when making an image uploaded with reactjs and nodejs?

I'm new to programming and I'm trying to set up an image uploader for my web app. I'm using node.js for the backend and react.js for the front end with mongodb as well. The problem is I'm getting a 404 ERR_NAME_NOT_RESOLVED whenever I try to upload the image.

I've tried a few things like changing the router name for the axios.post in react to no avail. I'm not sure what else to do at this point.

What I think is the relevant code is here:

react (upload-page.js):

fileUploadHandler = () => {
    const fd = new FormData(); 
    fd.append('photo', this.state.selectedFile, this.state.selectedFile.name); 
    axios.post('http://localhost8080/api/images', fd, {
      onUploadProgress: progressEvent => {
        console.log('Upload Progress:' + Math.round(progressEvent.loaded / progressEvent.total* 100) + '%')
      }
    })
      .then(res => {
        console.log(res); 
      });
    }

server.js:

app.use('/api/users/', usersRouter);
app.use('/api/auth/', authRouter);
app.use('/api/images/', uploadRouter);

router.js:

'use strict';

const express = require('express');
const multer = require('multer');
const upload = multer({dest: __dirname + '/uploads/images', storage: multer.memoryStorage() });
const Image = require('./models');

const router = express.Router(); 

//app.use(express.static('public'));

router.post('/', upload.single('imageField'), (req, res) => {
    if(req.file) {
        console.error(req.file);
        const i = new Image({
            data: req.file.buffer
        });
        i.save().then(() => {
            return res.status(201).json({
                id: i._id
            });
        }).catch(e => {
            console.error(e);
            return res.status(500).json({ message: 'error: ' + e.message})
        });
    }
    else {
        throw 'error';
    }
});

module.exports = router ; 

Full code can be found at these repos: Backend: https://github.com/beccaww/cats Frontend: https://github.com/beccaww/cats-client

I expect it to upload the image into the /images/uploads/images on the backend but it just gives me a 404 ERR_NAME_NOT_RESOLVED message instead. Any idea what might be going wrong?

Edit:

Okay, I fixed the axios.post('http://localhost:8080/api/images', fd, { , but now I'm getting a 500 error that says: POST http://localhost:8080/api/images 500 (Internal Server Error), followed by: Uncaught (in promise) Error: Request failed with status code 500. Any idea what might be causing this?

您应该在localhost和端口之间包含一个冒号(应该是localhost:8080 ,而不是localhost8080

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM