简体   繁体   中英

Axios post request failing with a 404

I'm using Axios to query an endpoint in my backend. When I try and do this, I get a 404 not found. If I copy/paste the uri it gives in the error from the console and try and access it directly in the browser it connects fine and does not give me an error (instead giving me an empty object which is expected).

Below is my Axios code

axios.post("/api/myEndpoint", { id: this.userID })
      .then((response) => { 
        this.property = response.data.property;
      })
      .catch((errors) => {    
        console.log(errors);    
        router.push("/");    
      });

Below is the route definition in my backend

const myEndpointRoute = require('../api/myEndpoint.js')();
exprApp.use('/api/myEndpoint', myEndpointRoute);

For reference, the uri is 'http://localhost:3000/api/myEndpoint'. I can access this uri completely fine in the browser but Axios returns a 404 as described above. It is for this reason that I'm confident this is an issue in the frontend, however I have set up this Axios request in the same way as the many others I have and they all work fine.

Edit: here's the rest of the backend

myEndpoint.js

module.exports = function() {
const express = require('express'), router = express.Router();
const authMiddleware = require('../loaders/authMiddleware.js')();

router.get('/', authMiddleware, async function(req, res) {
  const id = req.body.id;

  const property = await require('../services/myEndpointService.js') 
    (id).catch((e) => { console.log(e) });
    res.send({ property: property });
  });

  return router;
};

myEndpointService.js

module.exports = async function(id) {
  const results = await require('../models/getMyEndpointProperty')(id);

  return results;
};

getMyEndpointProperty

module.exports = async function(id) {
  const pool = require('../loaders/pool.js')();

  const res = await pool.query(`SELECT * FROM myTable WHERE id = ${id};`);
  return res.rows;
};

myEndpoint.js defines only a GET method but your axios call sends a POST in the frontend. Try changing (or adding) the express route:

// notice the `.post`
router.post('/', authMiddleware, async function(req, res) {
...
})

It worked when you manually tested it in the browser for this reason as well, since the browser sent a GET request.

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