Erorr with post request - reactjs

I am trying to do a challenge where I have to send this data through a post request to http://challenge-react.alkemy.org/
email: challenge#alkemy.org
password: react
const baseUrl = "http://challenge-react.alkemy.org/";
const user = {
'email': 'challenge#alkemy.org',
'password': 'react'
}
const getToken = async () => {
fetch(baseUrl, {
method: 'POST',
request: {"Content-Type": "application/json"},
body: JSON.stringify(user)
})
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log(err));
}
export default getToken;
For some reason that I can't understand, it is returning this to me
{error: "Please provide valid email and password"}
I don't know if my problem is with my function or what.
If I make this same request via postman, it returns the token I need

request should be headers.
See more here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_json_data

I don't think this will ever work in the browser because it keeps forcing the requests over HTTPS, erroring with: (unknown) POST https://challenge-react.alkemy.org/ net::ERR_SSL_PROTOCOL_ERROR. You can check for yourself by opening the console tab in developer tools (F12 on Chrome).
function App() {
const baseUrl = "http://challenge-react.alkemy.org";
const user = {
email: "challenge#alkemy.org",
password: "react",
};
React.useEffect(() => {
fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(user),
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.error(err)); // "oh, no!"
}, []);
return <div />;
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>

Related

request failed with status code 422 is returned by axios delete in react.js

I list some room_name from the backend with React.js
What I want to implement is that user can delete room_name when user clicks the trash can icon.
Issue/error message
Request failed with status code 422
It's strange
As shown in the picture, I can see "the body sent to server section" on the console.
I can confirm that the room_name has been sent properly.
I believe the data you are sending is correct.
Even if I try with Postman with the same URL and data, I can delete it successfully.
const SettingGetRoomName = () => {
const [room_name, setRoomName] = useState([]);
const DeleteRoom = async(data) => {
console.log("Body sent to server", {
home_rooms: [data.item],
})
await axios.delete("xxx.com",
{
home_rooms: [data.item],
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
alert('Succeded delete room!');
console.log('Succeded delete room!');
})
.catch(err => {
alert('Missed delete room!');
console.log(err);
console.log('Missed delete room!');
});
}
const getRoomName = async(data) => {
await axios.get("xxx.com",
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
console.log(result.data)
setRoomName(result.data.home_rooms);
})
.catch(err => {
console.log(err);
});
}
useEffect(() => {
getRoomName();
},[]);
return (
<>
{room_name.map((item,i) =>
<div key={i} className="flex_setting_get_room_box">
<div className="my_hubs">
<p className="">{item}</p>
<img src={ic_delete} onClick={(e)=>DeleteRoom({item})}/>
</div>
</div>
)}
</>
);
}
export default SettingGetRoomName;
Check this link and the axios docs. The second parameter of axios.delete() is not the request body, but rather the request options. Simply add the body on the data key of the request options:
await axios.delete("xxx.com", {
data: {
home_rooms: [data.item]
},
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
alert('Succeded delete room!');
console.log('Succeded delete room!');
})
.catch(err => {
alert('Missed delete room!');
console.log(err);
console.log('Missed delete room!');
});

Is it possible to use API Routes as Proxy to my existing RoR Backend

Every time NextJs request for an api, it will come first to api routes before it redirected to my RoR backend service.
I use this to encrypt my access token to session NextJS using iron-session once I get the data from backend.
## src/pages/api/login.ts
const loginRoute = async (req: NextApiRequest, res: NextApiResponse) => {
const response = await fetch(`backend-service/authorizations.json`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: req.body.username,
password: req.body.password
})
})
.then((res) => {
if (!res.ok) {
return res.text().then((text) => {
throw new Error(text)
})
}
return res
})
.then((res) => res.json())
.catch((err) => {
res.status(401).json({ message: err })
})
if (response) {
req.session.user = response
await req.session.save()
res.json(response)
}
}
export default withSessionRoute(loginRoute)
Is this a valid use case for API Routes in NextJS?
Thanks in advance!

When I fetch(url).then(console.log), the console.log does not execute

Hi I've been in a limbo with the problem. I'm trying to use the update method to update the iterations of clicks in my URL shortener project. The iterations update in the DB but then it isn't reflecting on the front end. I was thinking it would update in the then() function after fetching but then it seems like it didn't go in the then() function. My question is that is there something wrong with the code or is there an alternative way for it to get to the then()?
Client side (React)
const id = record._id;
fetch(`http://localhost:3001/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})
.then((res) => { <-- Not executing :(
console.log("Update");
// function to refresh the page
handleRefresh();
})
.catch((err) => {
console.log(err);
});
Server side (Mongoose)
urlControllerRouter.post("/update/:id", (req, res) => {
const id = req.params.id;
UrlModel.findById(id)
.then((updateURL) => {
updateURL.click = req.body.click;
updateURL
.save()
.then(() => {
console.log(`[UPDATE] ${updateURL}`);
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
});
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
});
});
Your server isnt making a response after getting the request from the client so the connection is pretty much in limbo for lack of a better word.
You need to send a response to client
urlControllerRouter.post("/update/:id", (req, res) => {
const id = req.params.id;
UrlModel.findById(id)
.then((updateURL) => {
updateURL.click = req.body.click;
updateURL
.save()
.then(() => {
console.log(`[UPDATE] ${updateURL}`);
res.status(200).json({
message: updateURL
})
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
res.status(500).json({
message: err.message
})
});
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
res.status(200).json({
message: err.message
})
});
});
Btw, with fetch you need to add two thens to get the data you want.
But in your case you don't want to get the data so one would do
So something like this
fetch(`http://localhost:3001/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})
.then(response => response.json())
.then((res) => { <-- Not executing :(
console.log("Update");
// function to refresh the page
handleRefresh();
})
.catch((err) => {
console.log(err);
});
Also you should actually add the backend link as a proxy value to your package.json as a better way of making the API call to the backend.
"name": "",
"version": "",
"main": "",
"proxy": "http://localhost:3001", //note the proxy
"license": "",
....
Then you just need to do this with fetch
fetch(`/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})

Unhandled Rejection (TypeError): Cannot read property 'error' of undefined

I'm fairly new to React and I've been trying to create a SignUp page, however, I'm stuck in this error. Can someone give me any indication on what I should do in order to solve this error?
Signup Method:
// = Action =
// Sign up
export const signup = user => {
return fetch(
`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
}
Rewrite Signup method (ps: I only changed the .catch handler)
`
// Sign up
export const signup = user => {
return fetch(
`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err =>
console.log(err));
return err;
}
`
You need to wrap up your fetch logic inside a Promise to return a value to the caller.
export const signup = user => {
return new Promise((resolve, reject) => {
fetch(`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => response.json())
.then(jsonData => resolve(jsonData))
.catch(err => resolve({error: `something went wrong err : ${err}`}));
})
}
signup(user).then(data => {
if (data.error) {
// handle error case
} else {
// handle success case
}
})
Now your signup method will return a value. Your data variable won't be undefined anymore.
I hope it helps, feel free to add comments or ask me more details

I am getting a 400 status code error, from the server. The server is working fine

My client and server are setup locally right now. I am trying to register a user. Basically my server is working fine, as i checked using postman. The problem is, when I send the register request the server returns, 400 status code. This usually means there is an error in the client. I think there is an error in the headers.
import axios from 'axios'
export const register = newUser => {
return axios
.post('api/register', newUser, {
headers: { 'Content-Type': 'application/json'}
})
.then(response => {
console.log(response)
})
.catch(err => {
console.log(err)
})
}
export const login = user => {
return axios
.post(
'api/login',
{
email: user.email,
password: user.password
},
{
headers: { 'Content-Type': 'application/json' }
}
)
.then(response => {
localStorage.setItem('usertoken', response.data.token)
return response.data.token
})
.catch(err => {
console.log(err)
})
}
export const getProfile = () => {
return axios
.get('api/profile', {
headers: { Authorization: `Bearer ${localStorage.usertoken}` }
})
.then(response => {
console.log(response)
return response.data
})
.catch(err => {
console.log(err)
})
}

Resources