英文:
Getting error message when trying send request to server using axios
问题
I see that you're facing an issue with your code, specifically related to the "dashboard" route. It seems like you're trying to access the "/dashboard" route, but you're getting an error saying that there is no route with "dashboard." This could be due to a few reasons:
-
Route Configuration: First, ensure that you have configured your server routes correctly. In your code, the route is defined as
app.get("/dashboard", ...)
, which should match the route you are trying to access. Make sure there are no typos or inconsistencies. -
Middleware Order: The order in which you apply middleware matters. Ensure that your route handling for "/dashboard" is defined after you've configured passport authentication middleware. Passport's middleware should come before your route definitions to handle authentication properly.
-
Authentication State: Check that your authentication process is working as expected. If authentication fails, you might be redirected to a different route, which could explain why it can't find the "dashboard" route. Ensure that you are successfully authenticated before accessing the "/dashboard" route.
-
UUID Handling: Since you mentioned that you are setting the dynamic parameter/routing using UUID, ensure that you are generating and using UUID consistently in both your client-side and server-side code.
-
Error Handling: Implement error handling to catch any exceptions that might occur during route processing. This can help you identify the specific issue causing the error.
Without seeing the exact error message or stack trace, it's challenging to pinpoint the exact problem. However, these are common issues that can lead to the error you described. Double-checking these aspects of your code should help you troubleshoot and resolve the issue.
英文:
I have this code where im trying to create a dynamic route (localhost:3000/{ dynamicId}/userPage for each user but axios is returning me an error:
App.jsx
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import './App.css'
import LoginPage from "./pages/LoginPage"
import { BrowserRouter, Routes, Route } from "react-router-dom";
import HomePage from './pages/HomePage';
import SignUpPage from './pages/SignUpPage'
import UserPage from './pages/UserPage';
function App() {
return (
<>
<BrowserRouter>
<Routes>
<Route exact path="/" element={<HomePage/>}/>
<Route path="login" element={<LoginPage/>}/>
<Route path="signup" element={<SignUpPage/>}/>
{/* <Route path="userpage" element={<UserPage/>}/> */}
<Route path=":user/userpage" element={<UserPage />} />
</Routes>
</BrowserRouter>
</>
)
}
export default App
UserPage.jsx
import axios from "axios"
import Button from "../Shared/FormElement/Button"
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
function UserPage(props) {
const[isLoading,setIsLoading]=useState(false)
const[isLoggedin, setIsLoggedin]=useState(false)
const handleLoad=(event)=>{
//-----------------------------PROBLEM-----------------------------------
setIsLoading(true)
axios({
method: "get",
url: "api/dashboard",
})
.then((response) => {
console.log("UserLoggedin:",response.data)
setIsLoading(false)
setIsLoggedin(true)
if (!response.data)
{navigate("/login")
}
})
//-----------------------------------------------------------------------
}
const navigate = useNavigate();
useEffect(() => {
// // Code to run when the component mounts (page loads)
// // Add your event listener here
// window.addEventListener('load', handleLoad);
// // Code to clean up the event listener when the component unmounts (page unloads)
// return () => {
// window.removeEventListener('load', handleLoad);
// };
console.log("being called")
handleLoad()
}, []);
function handleclick(event){
axios(
{
method: "post",
url: "api/logout"
}
).then((response) => {
console.log(response.data)
if (!response.data)
navigate("/login")
})
}
return isLoggedin&&<div>
<h1>Hello User</h1>
<Button type="submit" style="primary" onClick={handleclick}> Logout</Button>
{isLoading &&<h2>Loading...</h2>}
</div>
}
export default UserPage
vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})
In my server
require('dotenv').config()
const { v4: uuidv4 } = require('uuid');
const bodyParser = require("body-parser")
const express = require("express")
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const app = express()
const mongoose = require('mongoose');
const cors = require('cors');
const bcrypt = require('bcrypt');
const session = require('express-session');
const saltRounds = 10;
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json());
app.use(cors())
PORT = process.env.PORT || 3000
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true,
}))
app.use(passport.initialize())
app.use(passport.session())
const authUser = (email, password, done) => {
Account.findOne({ Email: email }).exec()
.then((account) => {
if (account) {
bcrypt.compare(password, account.Password).then(function (result) {
if (result) {
done(null, { account }, { message: "Succesfull" })
}
else {
// console.log("Check password again",)
done(null, false, { message: "Invalid password" })
}
})
}
else {
// console.log("Check your email ",)
done(null, false, { message: "Invalid password" })
}
})
.catch((error) => done(error));
;
}
passport.use(new LocalStrategy({
usernameField: 'email', // define the parameter in req.body that passport can use as username and password
passwordField: 'password'
},authUser))
passport.serializeUser((userObj, done) => {
done(null, userObj.account.id); // Store only the user ID in the session
});
passport.deserializeUser((userId, done) => {
Account.findOne({ id: userId })
.exec()
.then((account) => {
done(null, { account });
})
.catch((error) => done(error));
});
const { Schema, model } = mongoose;
const MongooseConnect = async () => {
try {
const conn = await mongoose.connect(process.env.MONGODBBKEY);
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.log(error)
process.exit(1)
}
}
const user_accounts = new Schema({
id:String,
first_name: String,
last_name: String,
Email: String,
Password: String
})
const Account = model("Account", user_accounts)
app.post("/login", (req, res, next) => {
passport.authenticate("local", (err, user, info) => {
if (user) {
req.logIn(user, (err) => {
if (err) {
return next(err);
}
console.log(user, info);
console.log(req.isAuthenticated());
console.log(user.account.id);
return res.json({
id: user.account.id,
authentication: true,
});
});
} else {
console.log(user, info);
// Authentication failed
return res.json({
id: user.account.id,
authentication: false,
});
}
})(req, res, next);
});
//-----------------------------PROBLEM-----------------------------------
app.get("/dashboard",(req,res,next)=>{
console.log(req.isAuthenticated())
res.json(req.isAuthenticated())
//----------------------------------------------------------------
})
app.post('/logout', function(req, res, next){
req.logout(function(err) {
if (err) { return next(err); }
console.log(req.isAuthenticated())
res.json(req.isAuthenticated())
});
});
app.post("/signup", async (req, res, next) => {
Account.findOne({ Email: req.body.Email }).exec()
.then((account) => {
if (!account) {
bcrypt.hash(req.body.password, saltRounds).then(function (hash) {
const user = Account({
id:uuidv4(),
first_name: req.body.first_name,
last_name: req.body.lastname,
Email: req.body.Email,
Password: hash,
})
user.save()
});
console.log("User Created");
const Accountexist = false
res.json(Accountexist)
}
else {
console.log("Account Exist")
const Accountexist = true
res.json(Accountexist)
}
})
})
MongooseConnect().then
(app.listen(PORT, () => {
console.log(`Working in port ${PORT}`)
}))
})
I'm getting this error:
The id is generated through UUID that im setting as the dynamic parameter/routing. Why is it saying that there is no route with dashboard.
答案1
得分: 1
You need to add a leading slash to your URL in the axios call:
axios({
method: "get",
url: "/api/dashboard",
})
You can see in the log that the requested URL was: http://localhost:5173/{SOME-ID}/api/dashboard
, when you make a request client-side with axios
without a leading slash, the browser (or axios?) assumes you are trying to request some endpoint starting from the current page instead of an absolute path.
You will want to do the same for the api/logout
request, which is also without a leading slash.
英文:
You need to add a leading slash to your URL in the axios call:
axios({
method: "get",
url: "/api/dashboard",
})
You can see in the log that the requested URL was: http://localhost:5173/{SOME-ID}/api/dashboard
, when you make a request client-side with axios
without a leading slash, the browser (or axios?) assumes you are trying to request some endpoint staring from the current page instead of an absolute path.
You will want to do the same for the api/logout
request, which is also without a leading slash.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论