I am trying to communicate with my server that I run locally on vscode,
the client on a separate vscode window I have live server enabled(this should not matter I believe).
I keep getting 404 when I try to access the get all saves route.
Postman, shows the saves with the get route on localhost/saves but the server does not , and gives an 404.
I have looked around on stack and google, but did not found the solution or an idea to solve it.
Tried adding cors in the .use as well. but no changes.
Server side I have 2 files, 1 for the server itself, and the 1 that handles the routes.
server.js
dotenv = require('dotenv').config();
const express = require("express");
const app = express();
const serverRouter = require("./routers/serverRouter.js")
const dbRouter = require("./routers/dbRouter.js")
const cors = require("cors");
const port = 5500;
const mongoose = require('mongoose');
const uri = process.env.MONGO_URI;
const allowedOrigins = ["http://127.0.0.1:5500", "http://localhost:5500"];
app.use(express.json());
app.use(serverRouter)
.use(dbRouter)
.use(
cors({
origin: function(origin, callback) {
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
var msg =
"The CORS policy for this site does not " +
"allow access from the specified Origin.";
return callback(new Error(msg), false);
}
return callback(null, true);
}
})
);
mongoose.connect(uri)
.then(() => {
console.log("connected to mongoDb")
app.listen(port, () => {
console.log(`server started on port ${port}`);
});
}).catch((error)=>{
console.log(error);
});
dbRouter.js
const express = require('express');
const router = express.Router();
const cors = require("cors");
// const appRoot = require('app-root-path');
const ThemeSave = require('../../models/themeColor');
// const ThemeModel = require(`${appRoot}/models/themeColor`)
// const saves = [];
// const urlSite = "http:/127.0.0.1:5500"
router
.post("/saves", async (req, res) => {
try {
const themeSave = await ThemeSave.create(req.body);
res.status(200).json(themeSave);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
console.log(req.body);
// res.send(req.body);
})
.get('/saves', async (req, res) => {
console.log("trying");
try {
console.log("im here");
const themeSave = await ThemeSave.find({});
res.status(200).json(themeSave);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
})
.get('/saves/:id', async (req, res) => {
try {
const { id } = req.params;
const themeSave = await ThemeSave.findById(id);
res.status(200).json(themeSave);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
})
.put('/saves/:id', async (req, res) => {
try {
const { id } = req.params;
const themeSave = await ThemeSave.findByIdAndUpdate(id, req.body);
if(!themeSave){
return res.status(404).json({message: `cannot find save with ID: ${id}`});
console.log("hier");
}
// const updatedThemeSave = themeSave;
res.status(200).json(themeSave);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
})
.delete("/saves/:savename", async (req, res) => {
try {
const {savename} = req.params;
const saveNameToDelete = await ThemeSave.findOneAndDelete({"savename":{$regex: `${savename}`}});
if(!saveNameToDelete){
return res.status(404).json({message: `cannot find savename with name: ${saveNameToDelete}`});
}
res.status(200).json(saveNameToDelete);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
})
.get("/getsave/:savename", async (req, res) => {
try {
const { savename } = req.params;
console.log(savename);
const themeSave = await ThemeSave.findOne(JSON.parse(savename));
console.log(themeSave);
res.status(200).json(themeSave);
} catch (error) {
console.log(error.message);
res.status(500).json({ message: error.message });
}
}).patch("/saves/:savename", async(req,res)=>{
//update part of the savename object?
});
module.exports = router;
here is my try on the client side
function getSaveObject(){
const url = "/saves";
fetch(url)
.then(response => {
// {
//handle response
// console.log(`responce: ${response.json()}`);
return response.text();// <-- gives the error msg in html(tho saves is json)
})
.then(data => {
//handle data
console.log(`data: ${data}`);
return data;
}).then(responseData => {console.log("responseData"),console.log(responseData);})
.catch(error => {
//handle error
console.log("im here error!");
throw new Error(`HTTP error: ${error}`);
});
};
responce shows in 127.0.0.1:5500/saves
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /saves</pre>
</body>
</html>
and the json that comes from localhost:5500/saves is
[
{
"_id": "64e93d25ada563cc8dff0ff0",
"savename": "Save 2",
"textsize": 16,
"__v": 0
},
{
"_id": "64e93e6717c146671f1083bf",
"savename": "Save 6",
"textsize": 2,
"createdAt": "2023-08-25T23:51:03.598Z",
"updatedAt": "2023-08-26T01:07:12.166Z",
"__v": 0
}]
so what am I missing and how can I make it work.
2
Answers
I have it working now,
I added
on the route
I used http://lcoalhost:5500/saves as URL in the fetch.
and that seemed to solved the 404 error
you didn’t add the port from your url. You should call it localhost:5500/saves or 127.0.0.1:5500/saves both will work. But if you only call it 127.0.0.1/saves. Then surely that is a 404.