why i cant get an axios response in react? - node.js

so I'm having a problem getting data from my server to my front-end using axios.
as you can see in this picture I'm getting a response for the GET method for users/users.
this is my showUsers function
const showUsers = async (req, res) => {
await User.find({})
.then((user) => {
res.status(200).json(user);
})
.catch((error) => {
res.status(400).send(error);
});
};
this is my axios api export
import axios from "axios";
export default axios.create({
baseUrl: "http://localhost:8080/users",
});
and this is my useEffect
import api from "../api/users";
import { useState, useEffect } from "react";
export const LogIn = (props) => {
const { setIsNewMember } = props;
const [users, setUsers] = useState([]);
useEffect(() => {
const fetchUsers = async () => {
try {
const response = await api.get("/users");
setUsers(response.data);
} catch (err) {
if (err.response) {
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else {
console.log(`Error: ${err.message}`);
}
}
};
fetchUsers();
}, []);
I'm getting this error on the frontend
so although I'm getting it from the postman and other services I'm not getting it on the front.
any idea why is that happening?

Related

how to set headers in axios patch request in react js

Can someone tell me what mistake I am making or tell me how to set the header in axios patch request. when I am running the API through postman, everything is working fine but when I connect it with the front end, an error comes up saying that the JWT is not provided on the backend
here is the frond end code :
import React, { useEffect } from 'react';
import { useParams } from 'react-router';
import axios from 'axios';
const Loader = () => {
const parmas = useParams();
const { id } = parmas;
console.log(id);
useEffect(() => {
const fetchBags = async () => {
try {
const res = await axios.patch('http://localhost:4001/public/verify', {
headers: {
'Content-Type': 'application/json',
Token: id,
},
});
console.log(res);
console.log('CBM', { res });
} catch (error) {
console.log(error);
}
};
fetchBags();
}, []);
return <div>this is loader</div>;
};
export default Loader;
below is my backend code:
export const verifyUser = async (data) => {
const token1 = data.header("Token");
try {
const verified = jwt.verify(token1, getTokenSecret());
console.log(verified)
await userModel.verifyUser(verified);
return {
message: "success",
};
} catch (error) {
console.log(`Auth Service > verifyUser > ${error.toString()}`);
throw error;
}
};
this error is comming:
Error
From docs
axios.patch(url[, data[, config]])
As you can see you pass config in 3rd argument not 2nd.
const res = await axios.patch(
'http://localhost:4001/public/verify',
{}, // data (2nd argument)
{
headers: {
'Content-Type': 'application/json',
Token: id,
},
} // config (3rd argument)
)

How to fetch data from backend using axios?

I have created a backend server using expressjs. I have created a frontend client using react. But I can't merge them both when am trying to get data from backend using axios am getting an error.
This is my index.js from backend
const express=require("express");
const mongoose=require("mongoose");
const dotenv=require("dotenv");
const helmet=require("helmet");
const morgan=require("morgan");
const UserRoute=require("./routes/users");
const AuthRoute=require("./routes/auth");
const PostRoute=require("./routes/posts");
const cors=require('cors');
const app=express();
dotenv.config();
mongoose.connect(process.env.MONGO_URL,{useNewUrlParser: true},()=>{
console.log("Database connected successfully!!")
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
app.use(cors());
app.use("/api/user",UserRoute);
app.use("/api/auth",AuthRoute);
app.use("/api/post",PostRoute);
app.listen(8800,()=>console.log("server is running!!"));
This is my posts.js from backend server
const router = require("express").Router();
const User=require("../models/User");
const Post = require("../models/Post");
//create a post
router.post("/", async (req, res) => {
const newPost = new Post(req.body);
try {
const savedPost = await newPost.save();
res.status(200).json(newPost);
}
catch (err) {
res.status(500).json(err);
}
});
//update a post
router.post("/:id", async (req, res) => {
try {
const post = Post.findById(req.params.id);
if (req.params.id === req.body.userId) {
await post.updateOne({ $set: req.body });
res.status(200).json("The post has been updated!");
}
else {
res.status(403).json("You can update only your post!!");
}
}
catch (err) {
res.status(500).json(err);
}
});
//delete a post
router.post("/:id/delete", async (req, res) => {
try {
if (req.params.id === req.body.userId) {
await Post.findByIdAndDelete(req.params.id);
res.status(200).json("The post has been deleted!!");
}
else {
res.status(403).json("You can delete only your post!!");
}
}
catch (err) {
res.status(500).json(err);
}
});
//get a post
router.get("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
res.status(200).json(post);
}
catch (err) {
res.status(500).json(err);
}
});
//like a post
router.put("/:id/like", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post.likes.includes(req.body.userId)) {
await post.updateOne({ $push: { likes: req.body.userId } });
res.status(200).json("The post has been liked");
}
else {
await post.updateOne({ $pull: { likes: req.body.userId } });
res.status(200).json("The post has been disliked");
}
}
catch (err) {
res.status(500).json(err);
}
});
//timeline posts
router.get("/timeline/:userId", async (req, res) => {
try {
const currentUser = await User.findById(req.params.userId);
const userPosts = await Post.find({userId:currentUser._id} );
const friendPosts = await Promise.all(
currentUser.following.map(friendId => {
return Post.find({ userId: friendId });
})
);
res.status(200).json(userPosts.concat(...friendPosts));
}
catch (err) {
res.status(500).json(err);
}
})
module.exports = router;
This is my feed.js from frontend
import "./feed.css";
import Post from "../post/Post";
import Share from "../share/Share";
import { useState } from "react";
import { useEffect } from "react";
import axios from 'axios';
export default function Feed() {
const [posts,setPosts]=useState([]);
const [texts,setTexts]=useState([]);
useEffect(()=>{
const fetchPosts=async ()=>{
const res=await axios.get("post/timeline/63c29c2fe9a410383d4bcb98");
console.log(res);
};
fetchPosts();
},[])
return (
<div className="feed">
<div className="feedWrapper">
<Share/>
{/*{Posts.map((p)=>{
<Post key={p.id} post={p}/>
})}*/}
</div>
</div>
)
}
When I try to reload the react app it's showing this
GET http://locahost:8800/api/post/timeline/63c29c2fe9a410383d4bcb98 net::ERR_NAME_NOT_RESOLVED
dispatchXhrRequest # xhr.js:247
xhr # xhr.js:49
dispatchRequest # dispatchRequest.js:51
request # Axios.js:142
Axios.<computed> # Axios.js:168
wrap # bind.js:5
fetchPosts # Feed.jsx:13
(anonymous) # Feed.jsx:16
commitHookEffectListMount # react-dom.development.js:23150
commitPassiveMountOnFiber # react-dom.development.js:24926
commitPassiveMountEffects_complete # react-dom.development.js:24891
commitPassiveMountEffects_begin # react-dom.development.js:24878
commitPassiveMountEffects # react-dom.development.js:24866
flushPassiveEffectsImpl # react-dom.development.js:27039
flushPassiveEffects # react-dom.development.js:26984
(anonymous) # react-dom.development.js:26769
workLoop # scheduler.development.js:266
flushWork # scheduler.development.js:239
performWorkUntilDeadline # scheduler.development.js:533
Feed.jsx:15 Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
Console Image
API URL is not valid, hostname should be localhost instead of locahost

Cookies doesn't show up in my application ReactJS

Hello i'm trying to code auth for my app i'm using json web token the problem is when i send post request using postman i can see the cookie and access token in headers but in my application i can't see anything in my localstorage&cookies
Here is my code
authContext.js
import axios from "axios";
import { createContext, useEffect, useState } from "react";
export const AuthContext = createContext();
export const AuthContextProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(
JSON.parse(localStorage.getItem("user")) || null
);
const login = async (inputs) => {
const res = await axios.post("http://localhost:8800/api/auth/login", inputs, {
withCredentials: true,
});
setCurrentUser(res.data)
};
useEffect(() => {
localStorage.setItem("user", JSON.stringify(currentUser));
console.log(currentUser);
}, [currentUser]);
return (
<AuthContext.Provider value={{ currentUser, login }}>
{children}
</AuthContext.Provider>
);
};
in login.jsx
const [inputs, setInputs] = useState({
username: "",
password: "",
});
const [err, setErr] = useState(null);
const navigate = useNavigate()
const handleChange = (e) => {
setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value }));
};
const login = useContext(AuthContext);
const handleLogin = async (e) => {
e.preventDefault();
try {
await login(inputs);
navigate("/")
} catch (err) {
setErr(err.response.data);
}
};
console.log(err);
console.log(inputs);
I'm trying to solve the problem because i'm trying to create a basic social app i need accessToken to display posts in my feed easily

`useEffect` not being able to fetch data on component mount

I am trying to set an array of objects into dineIns after fetching them inside useEffect. What I understood is that there is some kind of delay in receiving the data because the state variable returns an empty array when I log it after fetching the data.
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import jwtDecode from 'jwt-decode';
function CheckIns() {
const [dineIns, setDineIns] = useState([]);
const navigate = useNavigate();
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
const user = jwtDecode(token);
if (!user) {
localStorage.removeItem('token');
navigate('/login');
} else {
async function UserData(user_email) {
const user_data = await axios
.get(`/api/users/${user_email}`)
.then((res) => {
const info = res.data.reservations;
setDineIns(info);
console.log(dineIns);
});
}
UserData(user.email);
}
} else {
navigate('/login');
}
}, []);
}
What needs to be corrected here to set the state in time?
set state is an async operation, which log the data after set it, will log the old value.
To ensure that the data set correctly, you can use setState again
const info = res.data.reservations
setDineIns(info)
setDineIns(prev => {
console.log(prev)
return prev;
})
Or you can use effect with dineIns dependence.
I think your code works fine.
You are expecting a Promise from the axios call but you are awaiting it.
Try to change your code like this:
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
const user = jwtDecode(token);
if (!user) {
localStorage.removeItem('token');
navigate('/login');
} else {
async function UserData(user_email) {
try {
const { data } = await axios.get(`/api/users/${user_email}`);
setDineIns(data.reservations);
console.log(dineIns);
} catch (err) {
console.log(err);
}
}
UserData(user.email);
}
} else {
navigate('/login');
}
}, []);

NodeJS Axios - Cant show my get request on screen

On this case I am trying to show the "_id".
I made the code based on this video.
But by just looking at his API I can see that his data is little different, how can I adapt it to work with my API
import "./App.css";
import axios from "axios";
import { useEffect, useState } from "react";
const App = () => {
const [leitura, setLeitura] = useState([]);
const getLeituraData = async () => {
try {
const data = await axios.get(
"https://estufaarduino.herokuapp.com/sistema/leituras"
);
console.log(data.data);
setLeitura(data.data);
} catch (e) {
console.log(e);
}
};
useEffect(() => {
getLeituraData();
}, []);
return (
<div className="App">
{leitura.map((item) => {
return <p>{item._id}</p>;
})}
</div>
);
};
export default App;

Resources