Post the following data using axios with help of picture - reactjs

With the help of this image I wish to construct an api call using axios post. While I am trying to get the data I'm facing error although the api is hitting the backend.
This is my code:
login = async() => {
let params = {
email: "abc#gmail.com",
password: "12342346667"
}
let res0 = await axios.post('https://example.com/authentication/api/Login', params)
.catch((error) => console.log('error', error));
}
Postman post method:
I am new to React.

Try this way
axios.post('https://example.com/authentication/api/Login', {
email: "abc#gmail.com",
password: "12342346667"
})
.then(function response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Related

Fetch POST request console.log not working correctly

While I can post data to my server, and the server console.log works, I cannot for the life figure out why the client side console.log isn't working. What am I missing here?
The Error: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Status: 200 OK
Request: {"hotSauceId":32,"presentation":5,"viscosityId":3,"spiciness":10,"Flavor_Notes":["Constituent Peppers"],"overall_rating":5,"lovedit":true,"taster_notes":"test"}
Looks json to me?
Submit Handler:
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://jyh:3000', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
"hotSauceId": sauce,
"presentation": presentation,
"viscosityId": viscosity,
"spiciness": spiciness,
"Flavor_Notes": flavor,
"overall_rating": overall,
"lovedit": loved,
"taster_notes": notes
}),
}).then(res => {
return res.json();
}).then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
};
Server Code:
app.post('/', async (req, res) => {
await Jyh.create({ // .create is a Sequelize method
hotSauceId: req.body.hotSauceId,
presentation: req.body.presentation,
viscosityId: req.body.viscosityId,
spiciness: req.body.spiciness,
Flavor_Notes: req.body.Flavor_Notes,
overall_rating: req.body.overall_rating,
lovedit: req.body.lovedit,
taster_notes: req.body.taster_notes
}).then(() => {
console.log('req.body: ', req.body);
}).catch((err) => {
console.log(err);
});
});
It should console.log the response in the client console, but instead I receive an error.
Github repository for the client and server app.

ReactJS is throwing an error when catching a response from .NET API

I am connecting my ReactJS web app to my .NET Api and I am receiving an error whenever REACTJS is receiving the response from the API.
Here is what the error is saying
The api is returning a STRING which is the JWT token. Here is the code for that particular task:
public IActionResult Login([FromBody] UserLogin userLogin)
{
var user = Authenticate(userLogin);
if (user != null)
{
var token = Generate(user);
return Ok(token);
}
else
{
return NotFound("User not found");
}
}
and here is the fetch method in REACTJS that is responsible for this task:
function getJWTToken(event) {
event.preventDefault();
const userCredentials = {
email: user_email,
password: user_password,
};
const url = Constants.API_URL_LOGIN;
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userCredentials),
})
.then((response) => response.json())
.then((data) => {
console.log("Success:", data);
})
.catch((error) => {
console.error("Error:", error);
});
}
I spent two hours already but I cannot figure out what to do in here since this is my first project using react and .net. Thank you for your help.
Since you are not receiving json but plain text, use response.text() to read the response
I solved my propblem now. Thank you to Stutje, he gave me the idea. Instead of using response.json() , response.text() worked.

i'm getting auth token response for linkedin in postman but don't know how to convert it into axios

i want to get post request response from axios if I have token code I'm able to do that in postman but not able to complete it in axios
here is the postman response and all the require data I have to pass in postman
what I did to get the response in react
React.useEffect(() => {
if (code) {
let configData = {
client_id: 'hjhdjd',
client_secret: 'e637833ndd',
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:3000/linkedin/callback',
code: code,
};
console.log(configData);
axios(
configData
)
.then((response) => {
console.log(response.data.results.bindings);
})
.catch(function (error) {
console.log(error);
});
}
}, [code]);
but after doing this I'm getting error given below
TypeError: Cannot read properties of undefined (reading 'protocol')
You must call methods of axios, in this case you should use post:
axios.post(url,configData).then((response) => {
console.log(response.data.results.bindings);
})
.catch(function (error) {
console.log(error);
});

How to send token through headers by using axios post method in react

In my react app i am using axios to perform the REST api requests.
But it's unable to send the Authorization header with the request.
Here is my code:
This is authentication.js
async login(data) {
try {
const res = await axios.post(`'http://localhost:5000'/api/login`, data);
this.subject.next(true);
return res;
} catch (error) {
throw error;
}
}
This is login.js
async handleSubmit(e) {
e.preventDefault();
try {
const res = await auth.login(this.state.data);
tokenService.saveToken(res.data.token);
this.setState({});
swal({
title: "Good job!",
text: "Login successfully!",
icon: "success",
});
}
catch (error) {
swal({
title: "incorrect or password!",
text: "Login failed!",
icon: "error",
});
}
}
You can use Axios to create an instance of it with the headers passed to it save in local storage. Then, use that instance to further make requests. In this way, you don't to include it in every request.
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
headers: {'Authorization': bearer <TOKEN_FROM_LOCALSTORAGE>}
});
Use the instance to make request
instance.get("users")
.then(res => {
console.log(res);
console.log(res.data);
})
You can use this instance and customize it according to your instance so that code won't repeat. For further reference
Store it in localstorage and then concatenate it with 'Bearer'
let bearer = 'Bearer ' + JSON.parse(localStorage.getItem('token'));
//payload is the data which you're trying to send to the api endpoint
axios({
method: 'post',
url: '/api-endpoint',
headers: {
Authorization: bearer
},
data: payload
})
.then(response => response.json())
.then(json => json)
.catch(error => {
throw error;
});
check if the user is authenticated to use the Get or Post requests made by them
isAuthenticated() {
const token = localStorage.getItem('token');
}
Use the token to make the post request
axios({
method: 'post',
url: ''http://localhost:5000'/api/login',
{ headers: {"authorization" : token} }
data: payload
}),
.then(response => response.json())
.then(json => json)
.catch(error => {
throw error;
});
Handle your login
async handleSubmit(e) {
e.preventDefault();
try {
const res = await auth.login(this.state.data);
tokenService.saveToken(res.data.token);
this.setState({});
swal({
title: "Good job!",
text: "Login successfully!",
icon: "success",
});
}
catch (error) {
swal({
title: "incorrect or password!",
text: "Login failed!",
icon: "error",
});
}
}
Why you don't use axios interceptors like this:
axiosInstance.interceptors.request.use(
config => {
config.headers.authorization = localStorage.getItem("token");
return config;
},
error => Promise.reject(error)
);
Or declared on https://github.com/axios/axios/issues/1383

Fetch request always returns network error

I almost finished creating React Native application, few days ago register action has stopped working.. I'm sending fetch request and it always returns network error altough there is 400 response and message that user exists, it stops there..
I'm destructuring the response and displays api response message instead of fetch network error but now it doesn't work. I'm doing the same for the login action and it works.
Could it be something with multipart/form-data ?
export const register = data => dispatch => {
dispatch(createUser());
const d = new FormData();
d.append("name", data.name);
d.append("email", data.email);
d.append("password", data.password);
d.append("avatar", data.avatar);
fetch(API_URL + "/register", {
method: "POST",
headers: {
"content-type": "multipart/form-data"
},
body:d
})
.then(response => response.json().then(user => ({ user, response })))
.then(({ user, response }) => {
if (!response.ok) {
console.log(response, user)
} else {
console.log(response, user)
}
})
.catch(err => {
throw err;
});
};
The api route works in Postman..
In this case, your using fetch which is Promise based incorrectly,
Try,
fetch(API_URL + "/register", {
method: "POST",
headers: { "content-type": "multipart/form-data" },
body:d
})
.then(response => {
console.log(response, response.json().user)
})
.catch(err => {
console.log(err)
});
Check the logs and see if it shows proper network response and debug from there.

Resources