hi i want to access the autorization header token access and store in a session storage when i do that it returns me null maybe i did some mistake in my code and i dont know where
login form function
submitHandler = (e) => {
e.preventDefault();
try {
fetch('http://localhost:8080/login', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(this.state),
}).then((response) => {
const jwtToken = response.headers.get('Authorization');
console.log(response);
if (jwtToken === null) {
sessionStorage.setItem('Bearer', jwtToken);
} else {
return response.json();
}
});
} catch (error) {
console.log(error);
}
console.log(this.state);
};
Related
I post a login informations to my server and getting authorized, but after I login I get the client information with another request, its not working. I thought its about the cookies but not sure. If its about cookies how can I get the cookies and the set it inside of 'GET' client request ?
I've tired to add credentials: "include"and the other options of credentials but did not work. I saw a package which is react-native-cookies but I could not implement it into my functions.
This is my Login Request :
export const postUserLogin = (email, password) => new Promise((resolve, reject) => {
try {
fetch('http://1xx.xx.xx.xx/login', {
credentials: "include",
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password
})
})
.then(res => {
res.json()
.then(jres => {
resolve(jres);
}).catch(e => {
reject(e);
})
}).catch(e => {
reject(e);
})
}
catch (e) {
reject(e);
}
})
And this is my getClient Information Request :
export const getClient = () => new Promise((resolve, reject) => {
try {
fetch('http://1xx.xx.xx.xx/', {
credentials: "include",
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
}).then(res => {
console.log(res)
res.json()
.then(jres => {
resolve(jres);
}).catch(e => {
reject(e);
})
}).catch(e => {
reject(e);
})
}
catch (e) {
reject(e);
}
})
I want to retrieve the JSON response from the api call I am doing. Example, I want to retrieve something like this:
{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}
This is my API call using fetch in react. (yes I know sending password in URL is bad, it's for a school project)
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then((res) => {
console.log(res); //I want to get the JSON stuff here
})
This is the API call I am calling.
app.get('/api/user/:user', function (req, res) {
// console.log(JSON.stringify(req));
// var user = req.body.user;
// var password = req.body.password;
var user = req.params.user;
var password = req.query.password;
console.log(user, password);
var result = { error: {} , success:false};
if(user==""){
result["error"]["user"]="user not supplied";
}
if(password==""){
result["error"]["password"]="password not supplied";
}
if(isEmptyObject(result["error"])){
let sql = 'SELECT * FROM user WHERE user=? and password=?;';
db.get(sql, [user, password], function (err, row){
if (err) {
res.status(500);
result["error"]["db"] = err.message;
} else if (row) {
res.status(200);
result.data = row;
result.success = true;
} else {
res.status(401);
result.success = false;
result["error"]["login"] = "login failed";
}
res.json(result);
});
} else {
res.status(400);
res.json(result);
}
});
When I do console.log(res) in the fetch call, this is what is printed:
Response {type: "basic", url: "http://localhost:3000/api/user/tim?password=123", redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: falseheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: "OK"type: "basic"url: "http://localhost:3000/api/user/tim?password=123"proto: Response
When I visit the website, the output is:
{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}
This is what I want.
In general, this is how you return the response body from the Promise.
fetch(`${baseUrl}/api/user/${user}?password=${password}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}})
.then(response => response.json())
.then(data=> {
console.log(data);
})
Try this way to parse the response:
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then(async (res) => {
const raw = await res.text();
const parsed = raw ? JSON.parse(raw) : { success: res.ok };
console.log(parsed);
})
In this case you can also add some checks for response statuses (if you want, of course) along with parsing the result JSON.
for you to get the JSON body content from the response, you need to use json()
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then((res) => {
const jsonData = res.json();
console.log(jsonData);
})
try this
fetch(${baseUrl}/api/user/${user}?password=${password},{
method:'GET',
headers: {
'Accept': 'application/json',
'Content-Type':
'application/json',
}}) .then(async(response ) => {
await response.json()
})
I want to use received data from server on client . I use a NodeJS Server with NextJS and React.
I use this function on the server:
function addEmailToMailChimp(email, callback) {
var options = {
method: 'POST',
url: 'https://XXX.api.mailchimp.com/3.0/lists/XXX/members',
headers:
{
'Postman-Token': 'XXX',
'Cache-Control': 'no-cache',
Authorization: 'Basic XXX',
'Content-Type': 'application/json'
},
body: { email_address: email, status: 'subscribed' },
json: true
};
request(options, callback);
}
The function will be run from this point:
server.post('/', (req, res) => {
addEmailToMailChimp(req.body.email, (error, response, body) => {
// This is the callback function which is passed to `addEmailToMailChimp`
try {
var respObj = {}; //Initial response object
if (response.statusCode === 200) {
respObj = { success: `Subscribed using ${req.body.email}!`, message: JSON.parse(response.body) };
} else {
respObj = { error: `Error trying to subscribe ${req.body.email}. Please try again.`, message: JSON.parse(response.body) };
}
res.send(respObj);
} catch (err) {
var respErrorObj = { error: 'There was an error with your request', message: err.message };
res.send(respErrorObj);
}
});
})
The try method is used to verify that an email address could be successfully saved to MailChimp. An appropriate message is sent to the client.
On the Client-Side, i use this function to receive and display the data from the server:
handleSubmit() {
const email = this.state.email;
this.setState({email: ""});
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
}).then(res => {
if(res.data.success) {
//If the response from MailChimp is good...
toaster.success('Subscribed!', res.data.success);
this.setState({ email: '' });
} else {
//Handle the bad MailChimp response...
toaster.warning('Unable to subscribe!', res.data.error);
}
}).catch(error => {
//This catch block returns an error if Node API returns an error
toaster.danger('Error. Please try again later.', error.message);
});
}
The problem: The email address is saved successfully at MailChimp, but the message is always displayed: 'Error. Please try again later.'from the .catch area. When i log the error from the catch area i get this:
TypeError: Cannot read property 'success' of undefined
Where is my mistake? I have little experience in Node.js environments. I would be very grateful if you could show me concrete solutions. Thank you for your replies.
With fetch theres no data property on the response. You have to call res.json() and return that promise. From there the response body will be read and deserialized.
handleSubmit() {
const email = this.state.email;
this.setState({email: ""});
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
})
.then(res => {
console.log(res); //to make sure the expected object is returned
if(res.data.success) {
//If the response from MailChimp is good...
toaster.success('Subscribed!', res.data.success);
this.setState({ email: '' });
} else {
//Handle the bad MailChimp response...
toaster.warning('Unable to subscribe!', res.data.error);
}
}).catch(error => {
//This catch block returns an error if Node API returns an error
toaster.danger('Error. Please try again later.', error.message);
});
}
Two things you need to change:
Call and wait for res.json() to get the response body as json object.
The result of 1. is your 'data' object that you can use directly
handleSubmit() {
//...
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
})
.then(res => res.json())
.then(data => {
if(data.success) {
//...
toaster.success('Subscribed!', data.success);
} else {
toaster.warning('Unable to subscribe!', data.error);
}
}).catch(error => {
//...
});
}
i already have this code on my express server:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization");
next();
});
app.use('/graphql', graphqlExpress(async(req) => {
let {user} = await getUser(req.headers.authorization);
return ({
schema,
pretty: true,
graphiql: true,
context: {
user
}
})
}))
I thought it was cors problem so I followed from this tutorial in enable-cors for express: https://enable-cors.org/server_expressjs.html
This code is how i process fetching:
let token = localStorage.getItem('token');
const fetchQuery = (operation, variables) => {
return fetch('/graphql', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': token,
},
body: JSON.stringify({query: operation.text, variables})
}).then(response => {
// A better error message for request timeouts
if (response.status === 504) {
return Promise.reject({
error: {
message: 'Request timed out'
}
})
}
return response.json()
}).then(responseJson => {
// https://github.com/facebook/relay/issues/1816
// https://github.com/facebook/relay/issues/1913
if (responseJson.errors) {
return Promise.reject(responseJson.errors[0])
}
return Promise.resolve(responseJson)
})
}
But, even though there's already a token after a user logs in, the authorization sent to server is always null?
localStorage.getItem("token") is not executing, probably due to getItem being an I/O operation, and how exporting works. Move it inside fetchQuery
const fetchQuery = (operation, variables) => {
const token = localStorage.getItem("token");
return fetch('/graphql', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': token,
},
body: JSON.stringify({query: operation.text, variables})
}).then(response => {
// A better error message for request timeouts
if (response.status === 504) {
return Promise.reject({
error: {
message: 'Request timed out'
}
})
}
return response.json()
}).then(responseJson => {
// https://github.com/facebook/relay/issues/1816
// https://github.com/facebook/relay/issues/1913
if (responseJson.errors) {
return Promise.reject(responseJson.errors[0])
}
return Promise.resolve(responseJson)
})
}
I have a oauth set up. But when I want to get the access token with the fetch() function it just returns an object with things like _bodyInit, _bodyBlob and headers. So I just cannot get a JSON object. I'm on Android if that matters in any way.
Code:
componentDidMount() {
Linking.getInitialURL().then(url => {
if(url) {
console.log(url);
const queries = url.substring(16)
const dataurl = qs.parse(queries);
if(dataurl.state === 'ungessable15156145640!') {
console.log(dataurl.code);
console.log(dataurl.state);
return code = dataurl.code;
}
}
}).then((code) => {
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
var access_token = res;
console.log(access_token);
});
});
}
You almost got it right, you are missing one step though!
fetch doesn't return a json object, it returns a Response object, in order to get the json object, you have to use res.json()
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
return res.json();
})
.then((json) => {
console.log(json); // The json object is here
});
It's a good practice to add a catch just in case something goes wrong.
.then((json) => {
console.log(json); // The json object is here
});
.catch((err) => {
// Handle your error here.
})