How do I get Axios to hit routes in monorepo? - reactjs

I am using a monorepo-styled build and I am struggling to get routes to hit properly. I am clicking my button:
const handleSubmit = () => {
console.log("button clicked");
axios.get('/', {
params: {
username: "John1904",
}
})
.then((res) => {
console.log(res.data);
});
};
And I am getting the index.ts file, which makes sense. When I attempt to use '/users or /users/, it doesn't work. I get
>GET http://localhost:3000/users?username=John1904 404 (Not Found)
>Uncaught (in promise) AxiosError {message: 'Request failed with status code 404'
This is in the browser console, while nothing else shows in my terminal.
My index.ts that is handling routes is:
const app: Express = express();
const port = process.env.PORT;
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use('/users', usersRouter);
app.use('/', (_req, res) => res.status(200).send('Service online'));
app.use(errorHandler);
app.use(notFoundHandler);
And my server/src/routes/users/router.ts file is:
const router = express.Router();
router.get('/', async (_req: Request, res: Response) => {
try {
const items = await UserService.findAll();
res.status(200).send(items);
} catch (e) {
res.status(500).send(unwrapRouterErrorMessage(e));
}
});
So why is my request not going into the app.use('/users', usersRouter);?

Okay, thanks for asking about the ports, because I checked the URL requests in the dev tools and it was all going through to the frontend and not hitting the backend. Everything was going to the port 3000 instead of 3006. For now I hardcoded the route to go to http://localhost:3006/ and it worked. Thanks again.

Related

AxiosError with Get Method give me 404 Error Page

When I request data from Mongoose, it shows me an error and tells me that the page does not exist, knowing that I tested the back-end in Postman and it succeeded. I also tested the react by fetching data from an external link and it succeeded. I do not know what the problem is?!
I try with this code
This is my back-end code
const app = require("./app");
const mongoose = require("mongoose");
app.set("port", process.env.PORT || 3000);
const mongoURI = "mongodb://localhost:27017/get-now";
mongoose.connect(mongoURI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
})
.then(() => console.log(`database connected`))
.catch(err => console.log(err));
const port = process.env.PORT || 3000;
app.listen(port, () => {console.log(`the server is ${port}`)});
routes.get("/alldata" , async (req, res) => {
try {
const foodDatas = await Data.find({})
res.send(foodDatas);
console.log(foodDatas)
} catch (error){
res.status(500).json({
Error: error
})
}
});
This is my front-end (Reactjs) code
const fetchData = async () => {
    axios.get('http://localhost:3000/alldata')
  .then((res) => {
    console.log(res.data)
}).catch (err => {
console.log(err)
})
    }
  useEffect(() => {
    fetchData()
  }, [])
All these don't work it give me Error 404 page with data: undefined
did you configure the cors in the app file?
if don't, please install cors.
and add:
const cors = require('cors')
also:
app.use(
cors({
origin: "*",
})
);
Note:
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources

invalid JSON error when clicking button in reactjs

I am trying to build a simple react page where there are two buttons at the beginning.
The first sends the string 'private' as response when clicked, the second sends 'public' as a response when clicked.
The two strings should come from a mongodb database. It's not done yet, because whenever I click on any of the buttons, I get the same error over and over again.
It's the following:
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
This project has a backend server with two GET requests and a react frontend.
You can see them below.
The frontend:
function PubPrivBtn() {
async function clickHandler(e) {
if (e.target.id === 'pubBtn') {
let response = await fetch('/api/public');
let result = await response.json();
console.log(result);
}
if (e.target.id === 'privBtn') {
let response = await fetch('/api/private');
let result = await response.json();
console.log(result)
}
}
return (
<div>
<button onClick={(e) => clickHandler(e)} id='pubBtn'>Public</button>
<button onClick={(e) => clickHandler(e)} id='privBtn'>Private</button>
</div>
)}export default PubPrivBtn;
And the backend:
import mongoose from "mongoose";
import express from "express";
import props from './porp.model.js'
const app = express();
app.use(express.json());
mongoose.connect('mongodb://localhost/auth', async (err, db) => {
if (err) {
console.log(err)
}
else{
console.log('Connected!')
}
app.get('/api/public', async (req, res) => {
let pub = await props.where("vis").equals("public")
console.log(pub);
res.send(pub)
})
app.get('/api/private', async (req, res) => {
let priv = await props.where("vis").equals("private")
console.log(priv);
res.send(priv)
})
})
app.listen(3001)
Plus the schema is const porp = new mongoose.Schema({ vis: String }).
I have tried to remake the whole project from zero (not like it was a big deal), but nothing changed, so I have to think the problem is not in my code. Or maybe I'm wrong and it's something obvious.
My "proxy": "http://localhost:3001", was in the wrong package.json. (the backend's)
I have replaced it to the frontend and it's now working perfectly fine.
Thanks #Konrad Linkowski! If I hadn't noticed it, your comment would have solved it for sure!

unexpected token in json at position 0 reactjs mongodb

///component
function Home() {
const [show, setShow]= useState([{name:'', info:'', airingDate:'', poster:''}])
useEffect(()=>{
fetch("/home")
//.then(res=> res.json())
.then(res => res.text())
.then(text => console.log(text))
})
return (
<div>
{show.map(a=>
<div>
<h2>{a.title}</h2>
</div>
)}
</div>
)
/////index.js
const TvShows = require("./models/TvShows");
const express = require("express");
const app = express();
const mongoose= require("mongoose")
const dotenv= require("dotenv");
const authRoute = require("./routes/auth");
const { application } = require("express");
const userRoute = require("./routes/users");
const commentRoute = require("./routes/comments");
const tvshowsRoute = require("./routes/tvshows");
const cors = require("cors");
app.use(cors());
console.log(".");
dotenv.config();
app.use(express.json());
mongoose.connect(process.env.MONGO_URL,{
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(console.log("connected to mongoDB"));
app.use("/auth", authRoute);
app.use("/users", userRoute);
app.use("/comments", commentRoute);
app.post("/api/home", tvshowsRoute);
app.use("/api/home", tvshowsRoute);
/*
app.get('/api/home', (req,res)=>{
TvShows.find().then((result)=>{
res.send(result);
})
})
*/
/*
app.use("/",(req,res)=>{
console.log("main url")
})*/
app.listen("3001",()=>{
console.log("backend running");
})
//////route
const router = require("express").Router();
const TvShows = require("../models/TvShows");
router.post("/api/home", async (req, res) => {
console.log("here")
try{
const newTvShow = new TvShows({
title: req.body.title,
poster: req.body.poster,
info: req.body.info
});
const savedTvShows = await newTvShow.save();
res.status(200).json(savedTvShows);
}catch (err) {
res.status(500).json(err);
}
}
);
router.route("/api/home").get((req, res)=>{
TvShows.find()
.then(foundShows=> res.json(foundShows))
})
module.exports = router;
when I change res.json with res.text I see my index.html page on console not the data I want to fetch from mongodb. This error is probably because I didn't use /api/ on root url but I couldn't figure it out where I should write it. I tried but didn't work. It would be so good if someone could've helped. Thank you so much.
Indeed, you are fetching the /home page of your front-end app.
Assuming the api is on a different server, you would need to call the address of that server.
If you have a set up locally with a nodejs server and a react app running separately, you should have them run on two different ports.
If you have react app on http://localhost:3000 (default), then change your api to listen on 3001, then in your react code above, you can use the full uri
http://localhost:3001/api/home
in your fetch call.
I'm making a lot of assumptions about how you have this set up, based on my own experience of local development for similar problems.

"Error: socket hang up" error displayed when using Postman with ReactJS and MongooseDB

I'm following a tutorial for setting up a React application with MongooseDB, Express etc. I'm using Postman for GET, POST. See code below (I've starred the password from the database string).
When I send GET HTTP://localhost:8001 it shows "hello world" which I expect.
When I send GET HTTP://localhost:8001/tinder/cards it hangs and eventually displays the error "Error: socket hang up".
When I send POST HTTP://localhost:8001/tinder/cards it hangs and eventually gives a 500 Internal Server error.
Can anyone point me in the direction of where to debug please? I'm guessing the connection works as when I send GET HTTP://localhost:8001 it shows "hello world".
Thanks again.
import express from 'express'
import mongoose from 'mongoose'
import Cards from './dbCards.js'
import Cors from 'cors'
// App Config
const app = express();
const port = process.env.PORT || 8001
const connection_url = `mongodb+srv://admin:*******#cluster0.iyemf.mongodb.net/tinder-db?retryWrites=true&w=majority`
// middlewares
app.use(express.json())
app.use(Cors())
// db config
mongoose.connect(connection_url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology:true,
})
// api endpoints
app.get('/', (req, res) => res.status(200).send("hello world"));
app.post('/tinder/cards', (req, res) => {
const dbCard = req.body;
Cards.create(dbCard, (err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.get("/tinder/cards", (req, res) => {
Cards.find((err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(200).send(data)
}
});
});
// listener
app.listen(port, () => console.log(`listening on localehost: ${port}`));
You should also add the urlencoded middleware:
app.use(express.json());
app.use(express.urlencoded({
extended: true,
}));

How to find a route in Express?

I am using Express and trying to check login credentials, It works fine when i use post request without route. But I am getting error when i use express route.
This is my index.js code
const app = express();
app.use(bodyParser.json());
mongoose.connect("mongodb://localhost/bookworm", { useNewUrlParser: true });
console.log("post request");
app.use("api/auth", auth);
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
app.listen(8080, () => console.log("Running on localhost:8080"));
routes/auth.js code,
const router = express.Router();
router.post("/", (req, res) => {
res.status(400).json({ errors: { global: "Invalid Credentials" } });
});
I am expecting, 400:Invalid Credentials. but i am getting
"TypeError: Cannot read property 'global' of undefined"
It seems you're not letting your app know that it has to use router in certain endpoints.
import express from 'express'
const app = express()
const router = express.Router()
router.post('/', (req, res) => {
res.status(401).json({ errors: { global: "Invalid Credentials" } });
})
app.use('api', router)
app.listen(8080, () => console.log('listening on 8080'))
Now you can call the endpoint like so: http://localhost:8080/api with a POST request and it should return you a 401 error
More info here: https://expressjs.com/en/guide/routing.html#express-router

Resources