Home > Software engineering >  POST http://localhost:3001/createPost 404 (Not Found) EXPRESS & REACT
POST http://localhost:3001/createPost 404 (Not Found) EXPRESS & REACT

Time:11-03

I'm trying to pass data through Axios, from a page created with React, to a Mongo database managed by an Express server. Saving to database works for users, but for posts I get these error messages:

POST http: // localhost: 3001 / createPost 404 (Not Found)

Uncaught (in promise) Error: Request failed with status code 404 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.onloadend (xhr.js:66)

Can anyone help me out? I will attach the code below.

App.jsx

function App(){
  return (
      <Router>
        <Route path="/" exact>
          <Home />
        </Route>

        <Route path="/new">
          <NewPostFromHome />
        </Route>
    </Router>
  );
}

index.js (server)

const app = express();
app.use(cors());
app.use(express.json());

//Database connection
mongoose.connect("mongodb://localhost:27017/codingWaifus", {useNewUrlParser: true}, function(err, db){
  if(err){
    console.log(err);
  }
  else{
    console.log("Connected to " mongoose.connection.name " on Port: " mongoose.connection.port);
  }
});
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));

app.use("/", require("./routes/userRoute"));
app.use("/new", require("./routes/postRoute"));

app.listen(3001, () => {
  console.log("running on port 3001");
});

postModel.js

const mongoose = require("mongoose");

const postsSchema = {
  title: String,
  body: String
}

const Post = mongoose.model("Post", postsSchema);

module.exports = Post;

postRoute.js

const express = require("express");
const router = express.Router();
const Post = require("../models/postModel");

router.route("/createPost").post((req, res) => {
  const title=req.body.title;
  const body=req.body.body;
  const newPost = new Post({
    title,
    body
  });
  newPost.save();
})

module.exports = router;

CodePudding user response:

it seems that the problem that you have is that the postRoute is under the

app.use("/new", require("./routes/postRoute"));

Here you can see that you used the "/new" route so the final Url would be

http: // localhost: 3001 / new / createPost

if you use this Url it should work properly

or you could also remove the "new" word to only keep this:

app.use("/", require("./routes/postRoute"));

for more details about this please check this documentation of middleware in express: https://expressjs.com/en/guide/using-middleware.html

  • Related