How to get data from api using axios - node.js

Postman gets the data correctly but axios get the wrong data, it receives the "Not found" but there is a record in DB.
react hook:
import axios from "axios";
import {useEffect, useState} from "react";
export default function useRoom(roomName) {
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [room, setRoom] = useState({})
useEffect(() => {
setLoading(true)
axios({
method: "POST",
body: {
"roomName": "test1"
},
withCredentials: true,
url: "http://localhost:4444/room",
}).then(res => {
setRoom(res.data)
console.log(res)
setLoading(false)
}).catch(e => {
setError(e.toString())
setLoading(true)
})
}, [roomName])
return {
error,
room,
loading
}
}
NODE JS:
app.post('/room', (req, res) => {
Room.findOne({roomName: req.body.roomName}, async (err, doc) => {
if (err) throw err;
if (!doc) res.send("No Room Found");
else {
res.send(doc);
}
})
})
Postman receives the data but the axios doesn't
I have the data in my db
What I get in the browser console:
How I use my hook:
If someone knows how to solve this issue please let me know

I'm not sure but maybe you should use 'data' instead of 'body' :
axios({
method: "POST",
data: { // <--- HERE
"roomName": "test1"
},
withCredentials: true,
url: "http://localhost:4444/room",
})

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)
)

why i cant get an axios response in react?

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?

POST http://localhost:8080/todo net::ERR_ABORTED 400 (Bad Request), how do I fix this?

I'm creating a to-do list that uses authentication and the todo has to connect to the MongoDB server. The bad request is because of syntax, probably the to-do list sending back from client-side to server-side. How do I fix this error?
This is the page the error is on: TodoPage.js
import React, { useState, useEffect } from 'react';
//components
import ToDoList from '../Components/ToDoList';
import ToDoForm from '../Components/ToDoForm';
function ToDoPage() {
const [toDoList, setToDoList] = useState([]);
const url = 'http://localhost:8080/todo';
useEffect(function effectFunction() {
fetch(url, {
method: 'POST',
mode: 'no-cors',
})
.then((response) => response.json())
.then(({ data: toDoList }) => {
setToDoList(toDoList);
});
}, []);
const handleToggle = (id) => {
let mapped = toDoList.map((task) => {
return task.id === Number(id)
? { ...task, complete: !task.complete }
: { ...task };
});
setToDoList(mapped);
};
const handleFilter = () => {
let filtered = toDoList.filter((task) => {
return !task.complete;
});
setToDoList(filtered);
};
const addTask = (userInput) => {
let copy = [...toDoList];
copy = [
...copy,
{ id: toDoList.length + 1, task: userInput, complete: false },
];
setToDoList(copy);
};
return (
<div className='App'>
<ToDoList
toDoList={toDoList}
handleToggle={handleToggle}
handleFilter={handleFilter}
/>
<ToDoForm addTask={addTask} />
</div>
);
}
export default ToDoPage;
The console says it is this block of code that is giving trouble.
useEffect(function effectFunction() {
fetch(url, {
method: 'POST',
mode: 'no-cors',
})
.then((response) => response.json())
.then(({ data: toDoList }) => {
setToDoList(toDoList);
});
}, []);

Why is react not posting res.json() to console?

I have tried so many thing but my react app is not recieving jsonData variable or res as a return from the node app. The app is working and printing to console on the node side but I can't get it to print onto the react side.
const submitForm = async (event) => {
event.preventDefault(); // Prevent default submission
const data2 = document.getElementById("miles").value;
const data =
"passenger_vehicle-vehicle_type_" +
carType +
"-fuel_source_" +
vehicleType +
"-engine_size_na-vehicle_age_na-vehicle_weight_na";
axios
.post(`http://localhost:8000/api/vehicle/`, { data, data2 })
.then((res) => {
const returnText = res.json();
console.log(returnText);
return res.json();
})
.then((jsonData) => {
console.log(jsonData);
return;
})
.catch((error) => {
console.log("got errr while posting data", error);
});
};
I edited out the api and api key.
var fetch = require('node-fetch');
exports.vehicle = (req, res) =>{
let status;
const { data, data2 } = res.body;
const values = {
"emission_factor": data,
"parameters": {
"distance": parseInt(data2),
"distance_unit": "mi",
},
};
fetch('https://AAAAAAAAAAAAAAAA', {
method: 'POST',
headers: {
'Authorization': 'Bearer MYAPIKEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
})
.then((res) => {
status = res.status;
return res.json()
})
.then((jsonData) => {
console.log(jsonData);
console.log(status);
return jsonData
})
.catch((err) => {
// handle error
console.error(err);
});
res.send(req.body);
}
Working code thanks for the help:
const submitForm = async (event) => {
event.preventDefault(); // Prevent default submission
const data2 = document.getElementById("miles").value;
const data =
"passenger_vehicle-vehicle_type_" +
carType +
"-fuel_source_" +
vehicleType +
"-engine_size_na-vehicle_age_na-vehicle_weight_na";
axios
.post(`http://localhost:8000/api/vehicle/`, { data, data2 })
.then((res) => {
console.log(res.data);
return;
})
.catch((error) => {
console.log("got err while posting data", error);
});
};
Node solution in comments.
The functions inside your then() statements need to return data e.g. then((res) => {return res.json()})
You have two problems here...
Client-side, you seem to be mixing up an Axios response with a fetch() Response. You want res.data, not res.json(). Since you've tagged this with reactjs, here is where you would set the data to a state value, eg
axios.post(...).then(res => {
setSomeState(res.data)
})
Server-side, you aren't waiting for your fetch request to complete. I'd recommend using an async function
exports.vehicle = async (req, res) => {
try {
const { data, data2 } = req.body
const values = {
"emission_factor": data,
"parameters": {
"distance": parseInt(data2),
"distance_unit": "mi",
},
}
// don't mix up the Express "res" with the fetch "response"
const response = await fetch('https://AAAAAAAAAAAAAAAA', {
method: 'POST',
headers: {
'Authorization': 'Bearer MYAPIKEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
})
if (!response.ok) {
throw new Error(`${response.status}: ${await response.text()}`)
}
res.json(await response.json()) // respond with the data
} catch (err) {
console.error(err)
res.status(500).send(err)
}
}

React Native app Cannot Fetch data from Firestore using Api NodeJS

This is React native expo mobile app. I'm using NodeJs Server to get data from Firestore. Postman api fetch data properly.
Cannot fetch data from react native mobile app.
Postman Output
"customer": [
{
"phone":12345,
"username": "customer1",
},
]
Redux action.js
import { SET_CUSTOMERS } from "../types";
import { create } from "axios";
import { auth } from "../../firebase";
const baseURL = "https://...../api/";
const API = create({
baseURL: baseURL,
timeout: 60000,
"Content-Type": "application/json",
});
export const getCustomers = () => {
return async (dispatch) => {
try {
const token = await auth.currentUser.getIdToken();
console.log("token ", token); //Working Well
const response = API({
url: "customers",
headers: {
Authorization: `Bearer ${token}`,
},
});
console.log(response); //NOT Working
dispatch({ type: SET_CUSTOMERS, payload: response.data });
} catch (error) {
console.log(error);
throw error;
}
};
};
Redux reducer.js
import { SET_CUSTOMERS } from "../types";
const initialState = {
customers: [],
};
export default (state = initialState, action) => {
switch (action.type) {
case SET_CUSTOMERS:
return {
...state,
customers: action.payload,
};
default:
return state;
}
};
import React, { useState, useEffect, useCallback } from "react";
import { useSelector, useDispatch } from "react-redux";
import { getCustomers } from "../store/actions/data";
const UserProfileView = (props) => {
const [error, setError] = useState();
const customers = useSelector((state) => state.data.customers);
const dispatch = useDispatch();
const loadCustomers = useCallback(async () => {
setError(null);
try {
await dispatch(getCustomers());
} catch (err) {
setError(err.message);
}
}, [dispatch, setError]);
useEffect(() => {
loadCustomers;
}, [loadCustomers]);
return (
<View>
<Text>Customer Details</Text>
</View>
);
};
Expected Output payload: response.data pass response.data array
export const getCustomers = () => {
return async (dispatch) => {
try {
const token = await auth.currentUser.getIdToken();
console.log("token ", token); //Working Well
const response = API({
url: "customers",
headers: {
Authorization: `Bearer ${token}`,
},
});
console.log(response); //NOT Working
dispatch({ type: SET_CUSTOMERS, payload: response.data });
} catch (error) {
console.log(error);
throw error;
}
};
};

Resources