How to pass JSON object from API to server - node.js

I am using React and node.js, and I've used react's fetch to POST some Login credentials to my restAPI in order to receive a webtoken...
fetch('http://localhost:8080/api/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.username_login,
password: this.state.password_login
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson); //this is the object containing the token
})
.catch(function(error) {
console.log("request failed");
})
}
so responseJson is the the object containing my web token. The request was successful and now I've passed it to the client. Now, I am thinking of saving it to a cookie.
How can I send this to the server? Should I make a POST request? If so how do I do that once the JSON object is received? If there is a better way, I would like to know.

Cookies are automatically passed along any HTTP request made with fetch

Related

ReCAPTCHA siteverify not returning JSON response

I am implementing recaptcha into a user submittable form. After attempting to validate the token using the url
https://www.google.com/recaptcha/api/siteverify
The response given is something similar to
▼���RPP*.MNN-.V�RHK�)N�☺��▬§�↨�&秤�ģ�B#�̼�Ĝ�¶�̼��↕ݢ�����T%�d,W-�
� K
The code used to attempt to validate the response is as follows
var data = JSON.stringify({
secret: process.env.RECAPTCHA_SECRET,
response: req.body.gcaptcha_response,
});
var config = {
method: "post",
url: "https://www.google.com/recaptcha/api/siteverify",
headers: {
"Content-Type": "application/json",
},
data: data,
};
axios(config)
.then(function (response) {
res.json({
success: true,
body: response.data,
});
})
.catch(function (error) {
console.log(error);
});
I have also attempted with other content types to no success. I have also attempted to follow the answer given in this thread
This is a workaround for now
I just realised this is happening for the latest version of axios.
If you install axios version 1.1 it returns the data as json.
Thread: https://github.com/axios/axios/issues/5298

Node.js? API Authentication problems

This is what my "dev" sent me. Someone help please
I'm trying my best, but their API doesn't respond to our methods. This authentication is the root of the problem. I'm right now using Axios(the most popular and only method for making API requests for web apps) but it's not accepting request
and then i told him i would ask for help*
You can ask this question- ` How do I make requests for creating order API in my express app? I've tried to make the request by getting my form data from my EJS form using the request.body. But still, it is saying error 400.
Here is his code:
app.post('/order-labels', checkAuthenticated, (req, res) => {
const data = JSON.stringify(req.body);
console.log(data)
const config = {
method: 'post',
url: 'https://labelsupply.io/api/order',
headers: {
'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
axios(config)
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
})
by console.logging we are getting the data, but the API doesn't accepting
The API Docs are here.
you may need an account to view just put junk
The API calls for url encoded string.
const data = JSON.stringify(req.body);
console.log(data)
data = new URLSearchParams(Object.entries(data)).toString();
console.log(data); // now should be URL encoded
const config = {
method: 'post',
url: 'https://labelsupply.io/api/order',
headers: {
'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
See if the API likes the new encoding?

Basic Auth is not working with Axios post Nodejs

I am trying to send a request using axios post with basic authorization. It is working fine with postman but not working when I try to send via code.
axios.post(`my-url`, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic **KEY_HERE**',
},
data: {
'id': 'event_order',
'date': '2021-09-09'
}
}).then(async (response) => {
console.log(response.data)
})
It is returning 401 Unauthorized. But, it works as excepted when I call it via Postman:
Postman Setup Image
Did you add your domain to whitelist in your cors module? If not:
app.use(cors({ origin: "PROTOCOL://DOMAIN:PORT", credentials: true }));
edit: Ok, sorry, I was confused and thought you were sending a frontend axios post request to your own NodeJS server. If possible, could you be more precise. But try passing in your headers/auth as the third argument-- since you're passing in everything in the second argument, the API is not parsing out your headers since its part of the data parameter.
const data = {
'id': 'event_order',
'date': '2021-09-09'
}
axios.post(`my-url`, data, {
headers: {'Content-Type': 'application/json'},
auth: {
username: "YOUR_USERNAME",
password: "YOUR_PASS"
}
})
.then(async (response) => {
console.log(response.data)
})
Also try and post the network errors, if you can.

How can I use state to make a POST fetch request on my backend

I'm working on my first app right now which I created in react native for the front end and using Node JS as a backend and mongodb for the database.
I'm trying to implement register form for my user but I don't really know how to do this with the state because it keeps saying cannot evaluation this.state.name.
What I want to do is a POST request using fetch api to register an account it works using Postman so the error come from my front end.
So what I do is I create my function to do that but I want the body to represent the value the user typed in the different field which I store in the state when you'll see the code it will be clear.
If I use the state it does not work however if I put some value directly in my function it works.
This first thing is my function with the fetch API if I do this it does not work, below is how I get the state of each field (see the )
clickthebutton = () =>{
//var data = this.state
fetch('http://localhost:5050/api/new/register',{
method:'POST',
headers : {'Content-Type': 'application/json'},
body : {
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
},
})
}
<Input
label="Your email address"
placeholder="yo#gmail.com"
onChangeText={(text)=> this.setState({email:text})}
value={this.state.email}
>
My state looks like this :
this.state={
email:null,
password:null,
name:null,
age:null,
dataImage:null
}
I would like to send the body, if I do body : this.state it does not send anything when I do a console.log(req.body) on my server it shows an empty object.
Thanks for any help
EDIT : Problem fixed, my function was not referring to my class.
First of all you need a correct element for your email and password inputs, for example (for email):
<TextInput
value={this.state.name}
keyboardType={'email-address'}
placeholder="Your email address"
onChangeText={text => this._onEmailChange(text)}
/>
you also need a function to update the name value (you will need a similar function to update any value coming from a TextInput element)
_onEmailChange = text => {
this.setState({ name: text });
};
Then you can prepare your request as follow
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.name,
password: this.state.password
...
}),
})
.then(response => response.json())
.then(responseJson => {
// do what you want with the response here
})
.catch(error => {
console.error(error);
});
You have specified in the header that you send in json format when you send. When sending to the server, you must convert to jsonString.
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
}),
});
Ok You can try use Formdata
let formdata = new FormData();
formdata.append("name", this.state.name);
formdata.append("age", this.state.age);
formdata.append("password", this.state.password);
formdata.append("email", this.state.email);
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data"
},
body: formdata
})
.then(res => res.json())
.then(reponse => {
console.log(reponse)
})
.catch(error => {
console.error(error);
});
After getting all form-data in your state you have two options to make a request to backend.
Either set Content-Type As application/text or remove header.
fetch('http://localhost:5050/api/new/register',{
method:'POST',
headers : {'Content-Type': 'application/text'},
body : {
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
},
})

Unexpected token N in JSON at position 0

guys. I have a than error in my NodeJS rest API, and can't resolve this.
My idea is make a github login, this app working like this.
Href to github url returning a temporal code in callback.
Latter, send this temporal code to my REST API and with rest api make a fetch request to other endpoint of the github api, and this endpoint should return access_token=12345 (this access token is a example), for latter send this token to frontend, and convert the token in a JWT token and also send to frontend for latter storage in a localStorage to use it.
My code in NodeJS
router.post("/users/github/:code",function(req,res){
fetch('https://github.com/login/oauth/access_token/', {
method: 'GET',
client_id: 'xxxx',
client_secret: 'xxxx',
code: req.params.code,
accept: 'json',
})
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
});
PD: I use node-fetch module for this. https://www.npmjs.com/package/node-fetch
The solution
router.post("/users/github/:code",function(req,res){
fetch('https://github.com/login/oauth/access_token/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: 'xxxx',
client_secret: 'xxxx',
code: req.params.code
})
}).then(function(res) {
return res.json();
}).then(function(body) {
res.json(body);
});
});

Resources