How to change local address in fetch API React - node.js

I have a local API which is hosted in http://127.0.0.1:8080 and React server is in http://127.0.0.1:5500. I want to design a user interface for the API by a React webpage. But React puts its local address in front of the Get Api like http://127.0.0.1:5500/public/127.0.0.1:8080/lst/users. Even if I just put /lst/users in the fetch method address and define a proxy "proxy": "http://127.0.0.1:8080" in the app.json, the React will try to get http://127.0.0.1:5500/lst/users. How should I fix this.
// get all entities - GET
fetch('127.0.0.1:8080/lst/users', {
"method": "GET",
mode:'no-cors',
url:'http://127.0.0.1:8080',
credentials:'include'
})
.then(response => response.json())
.then(response => {
this.setState({
friends: response
})
})
.catch(err => { console.log(err);
});

You need to add the protocol else it will be treated as relative path.
add "http" => http://127.0.0.1:8080
E.g.
fetch('http://127.0.0.1:8080/lst/users', {
"method": "GET",
mode:'no-cors',
credentials:'include'
})
.then(response => response.json())
.then(response => {
this.setState({
friends: response
})
})
.catch(err => { console.log(err);
});

Related

How to Adding a properties to a incoming response data?

initPayment giving me response data,which is actually came from a payment gateway.So i need to add a properties to this response data.So that i can get this properties with the response data. How can i do that?
useEffect(() => {
initPayment(userInfo.token)
.then((response) => {
if (response.data.status === "SUCCESS") {
setSessionSuccess(true);
setRedirectUrl(response.data.GatewayPageURL);
setFailed(false);
}
})
.catch((err) => {
setFailed(true);
setSessionSuccess(false);
console.log(err);
});
}, [userInfo.token]);

How to make GET request with MERN Stack

I'm trying to fetch data from database. Everything I got from response is this:
Response {type: "cors", url: "http://localhost:5000/products/", redirected: false, status: 200, ok: true, …}
I need help for how to make the request in frontend and backend:
Here is ReactJS side:
getProducts() {
fetch('http://localhost:5000/products/', {
method: "GET",
})
.then(response => console.log(response))
.then((response) => {
console.log(response.data)
this.setState({products: response.data});
})
.catch((error) => {
console.error(error);
});
}
Here is my server side for the request:
router.get('/', (req, res) => {
productService.getAll(req.query).then(products =>{
res.status(200).json(products)
}).catch(() => res.status(500).end())
})
Here is the productService:
async function getAll(query) {
let products = await Product.find({}).lean()
return products;
}
P.s.: the products are creating without errors in MongoDB Compass:
You should call response.json() to extract the JSON body from the response stream and return it to the next then block in the chain. And you can omit the method configuration since it is GET by default.
fetch('http://localhost:5000/products/')
.then((response) => response.json())
.then((products) => {
this.setState({ products })
})
Btw, you shouldn't hardcode the API URL. Use environment variables. If you're using Create React App, you can add environment variables prefixed with REACT_APP_ to .env or you can use dotenv-webpack if you have a custom Webpack setup.
fetch(`${process.env.BASE_API_URL}/products`)
.then((response) => response.json())
.then((products) => {
this.setState({ products })
})

How to make 2 POST request from a react form

I have made a react form and want to make a post request to webhook.site with the form data. If I receive a 200 status code then I want to send the form data to a backend express server for further operation.
I am using axios to make the POST request.
This is the axios snippet from my react form:
import React, { Fragment, useState } from "react";
import axios from "axios";
const Form = () => {
const [candidate, setCandidate] = useState({
fullName: "",
phoneNumber: 0,
email: "",
gitProfile: "",
linkToResume: "",
designation: "",
interest: "",
});
const onChange = e =>
setCandidate({ ...candidate, [e.target.name]: e.target.value });
const onSubmit = e => {
e.preventDefault();
axios
.post("http://localhost:5000/", {
candidate,
})
.then(res => {
console.log(res, candidate);
});
};
Currently i am directly sending data to the backend. I have individually checked posting to both the webhook.site and backend, the code is working fine. But I want to do it simultaneously. If I get a 200 status code after posting to webhook.site, then only I want to send the form data to backend.
axios
.post("http://localhost:5000/", {
candidate,
})
.then(res => {
console.log(res, candidate);
// Write your another post request here because if your first request return 200 statusCode it will execute this function otherwise it will go catch function
}).catch(error => {
// if your first request failed then it execute this function. Here you can get error message.
console.log(error);
});
Check if first POST return status 200, then call next request.
axios
.post("http://localhost:5000/", {
candidate,
})
.then(res => {
console.log(res, candidate);
if (res.status === 200) {
axios.post('/url', {data})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}).catch(function (error) {
console.log(error);
});

How to send React to Express server get Request passing id

Hello I am learning on MERN Stack dev, so I am trying to implement a get request where by I send in and ID and then try searching through the collection by the id the return the entry back to the client so I have been trying to implement this but I do not know where I am going wrong because I get a 404 response
Code below is the client side where I try to send through the get request
const ProductDetails = (props) => {
const product_id = window.location.href.split("/")[4];
console.log(product_id);
const getProduct = () => {
const url = `http://127.0.0.1:5000/single-women-clothes/id?=${product_id}`;
Axios.get(url)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
};
getProduct();
return (
<div>
<h1>Details</h1>
</div>
);
};
router.get("/single-womens-clothes/:id", (request, response) => {
console.log(request.params);
MongoClient.connect(
mongoURI,
{ useNewUrlParser: true, useUnifiedTopology: true },
(error, client) => {
client
.db("OnlineStore")
.collection("WomensClothes")
.find(request.params.id)
.toArray()
.then((data) => {
response.status(200).json(data);
})
.then((response) => {
console.log("Single Female Product Fetch Successful");
})
.catch((error) => {
console.log(error);
});
}
);
});
Can I please get help on how I can pass the ID to the server then search through collection through this given ID
Anytime you have a 404 error, the issue is usually coming from putting the wrong url.
In your front-end:
single-women-clothes/id?=${product_id}
Backend
/single-womens-clothes/:id
You are missing an "s" in the front-end url in "womens"
To answer your second question:
You shouldn't do id?= just simply leave it as
single-women-clothes/${product_id}

POST request with Axios not sending data to my server

Here is my React code for the form submission:
const handleSubmit = (e) => {
e.preventDefault();
console.log('item:', item);
Axios.post('http://<MY_SERVER>/item/add', {name:item})
.then(response => console.log(response))
.catch(err => console.log(err));
};
and this is the code in my Node API:
// Add a new Item
app.post('/item/add', (req, res) => {
const newItem = new Item({
name: req.body.name
});
newItem.save()
.then(item => {
res.json({msg: 'success'});
})
.catch(err => console.log(err));
});
When I run the handleSubmit nothing happens. I only get the console.logs... Also, here is the error from my server
'ValidationError: item validation failed: name: Path' `name` is required
So it is clear that the data sent over to the api is never received. I've tried changing it up in many ways I have came across online but no luck.
I have attached both ways to post data i.e. Form URL Encoded and JSON. For sending Form Url Encoded data we need an additional Library querystring.
You can install it using npm install query-string
Here is the code for both the requests. You don't need query-string if you are using content type application/json.
Here you go
var axios = require('axios');
const qs = require('querystring');
function sendFormUrlEncodedData() {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
const payload = {
name: 'morpheus',
job: 'leader'
};
//Send data with form url using querystring node package for it.
axios
.post('https://reqres.in/api/users', qs.stringify(payload), {
headers: headers
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
function sendJSONData() {
const headers = {
'Content-Type': 'application/json'
};
const payload = {
name: 'morpheus',
job: 'leader'
};
//Send data with JSON, so stringifying it.
axios
.post('https://reqres.in/api/users', JSON.stringify(payload), {
headers: headers
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
sendFormUrlEncodedData();
sendJSONData();
First of all check whether your backend code is working or not by using postman. I think you are getting validation error because of the error of your backend code. And also check whether that you are implemented the name attribute correctly with its data type.
After that update, the react code as below.
import axios from 'axios';
constructor() {
this.item = {
name: ''
}
}
handleSubmit(event) {
console.log('item:', this.item.name);
event.preventDefault();
axios.post('http://<MY_SERVER>/item/add', this.item)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}

Resources