I've tried to access x-auth token from server.But I'm not getting the expected result.The consoled output of response.headers from server is as follows
Headers {
map: {
connection: "keep-alive"
content-type: "application/json; charset=utf-8"
x-auth: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiIxaXBpNG1laiIsImFjY2VzcyI6ImF1dGgiLCJpYXQiOjE1NTY3MDg1NTR9.cOXtbQO_n2vf-HwLmKwyzSi9QcFgh4SghfgCamcLyw4"
x-powered-by: "Express"
}
}
I've tried to console x-auth but I got error auth is not defined.But when I consoled response.headers.map.connection I got the value.Following is the code I've tried so far
fetch(GLOBAL.LOGIN, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"requestHeader": {
type: "login"
},
"loginData": {
email_id: this.state.email_id,
password: this.state.password
}
})
}).then((response) => {
console.log(response.headers.map.x-auth);
})
I don't know how to access the token.Please help.
In your .then handler you should be able to access header elements like the following:
console.log(response.headers.get("x-auth"));
Related
I have gone through many posts and tested most of them but I still get this error.
It's interesting that I don't get this error for the get method. I get this error only for put method.
thanks to everyone
axios error 401 (Unauthorized)
axios
.put("/api/v1/Profile", {
fullName: userName,
gender: Number(userGender),
phoneNumber: userNumber,
headers: {
Accept: 'application/json',
"Content-Type": "application/json; charset=UTF-8",
Authorization: `Token ${userToken}`,
},
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
There is no error for the get method, but it gives an error for the put method
I tested it with Postman and it works without errors
There is something wrong with your Authorization header. You're using the right syntax (see MDN):
Authorization: <auth-scheme> <authorization-parameters>
Given userToken is your <authorization-parameters>. The problem comes from the <auth-scheme> for which you used Token: this is not a valid scheme according to the list maintained by IANA.
Hard to be sure without much information, but I guess what you want is:
Authorization: `Bearer ${userToken}`,
My problem was solved with this format:
axios({
method: 'put',
url: 'api/v1/Profile/',
data: {
fullName: userName,
gender: Number(userGender),
phoneNumber: '',
},
headers: {
'Content-Type': 'application/json; charset=UTF-8',
Authorization: `Bearer ${userToken}`,
},
}).then((response) => {
console.log(response);
});
I am new to React, And I am Stuck. I am trying to make a signup page, having textboxes: name,phonumber,email,password.
What I want is, When I click on login button, all these details should be sent over POST to my API, and response is fetched and stored.
API:
http://localhost:5000/api/users/signup
Method:
POST
Request to my api is send in this way:
content-type: application/json
{
"name": "Devanshh Shrivastvaaaa",
"phoneNumber":"982964XXX8",
"email": "devannnnnshh;#ccc.in",
"password": "1234566788"
}
Can anyone please explain me using code how to send this data to my api on clicking signup, and fetching response
Don't need to use any third party libraries, just use the Javascript fetch API
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
Source: Mozilla MDN
you need to install axios or fetch axios is good axios
axios.post('http://localhost:5000/api/users/signup', {
name: "Devanshh Shrivastvaaaa",
phoneNumber":"982964XXX8",
email: "devannnnnshh;#ccc.in",
password: "1234566788"
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
also check for further
I have an API endpoint working good in postman with the bellow options
The above request can get 200 status and got a response. Now I am trying to implement the same API with React Native using fetch method.
fetch('https://example.com/api/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Token':'xxxxxx-xxxx-xxxx-xxxx-xxxxx'
},
body: {
"useremail": "testuser#example.com",
"userpassword": "123456"
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
}).catch((error) =>{
console.error(error);
});
The above code was not working and I am getting 403 status.
Have you tried this
The easy way to implement this is to use this attribute to your AndroidManifest.xml where you allow all http for all requests:
android:usesCleartextTraffic="true"
feel free for doubts
You are passing data without converting it to json will make problem here
fetch('https://example.com/api/user/login', {
method: 'POST',
credentials : 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'token':'xxxxxx-xxxx-xxxx-xxxx-xxxxx',
},
body: JSON.stringify({ // convert object to json
"useremail": "testuser#example.com",
"userpassword": "123456"
}) ,
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
}).catch((error) =>{
console.error(error);
});
HTTP 403 is a standard HTTP status code communicated to clients by an HTTP server to indicate that access to the requested (valid) URL by the client is Forbidden for some reason. The server understood the request, but will not fulfill it due to client related issues.
so for first step in your postman use a fake user password to see if you get 403 again ,
if you got, that means you have problem in your sending your react native data.
so you should focus on your sending request code then,
According to docs
you can post like this
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
be sure that you are sending your user pass correctly and not missing anything like misspellings
hope this helps you.
I want to post data to the server using headers content-type: 'application/xww-form-urlencode' but it fails because of the content type change to application/json
var headers= {
'content-type': 'application/x-www-form-urlencoded',
'x-access-key': 'key'
}
var data = {
'twins' : twins
}
axios.post('url', data, { headers: headers })
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
With Postman I successfully added the entry
In your headers change content-type to
'Content-Type': 'application/x-www-form-urlencoded'
If this doesn't work, then you I feel you might be using an interceptor. Which might be overriding your configuration.
I cant send my data in json format.
In the server which i was using will accept only json body.
fetch('url', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
FirstName: this.state.name,
LastName: this.state.last,
EmailAddress: this.state.emails,
Phone: mobis
})
}).then((response) => {
alert(response);
console.log(response)
}).catch((error) => {
console.log(error);
alert(error)
});
am using the above code to pass the data as json
but its not going
the response which am getting is
[object Response]
by using console.log, i got a error is
Response {
type: "cors",
url: "https://api-in21.leadsquared.com/v2/LeadManagement.svc/Lead.Create?accessKey=u$raabd4c6e4e7953f215a7235495367a49&secretKey=a351cd31591c76f19642202ce97cd9417f1c46aa",
redirected: false,
status: 500,
ok: false,
statusText: "Internal Server Error",
headers: Headers,
bodyUsed: false
}
pls suggest me some code guys
You can also try this code
return fetch(HOSTNAME, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ variables: { input: data}})
})
.then((res) => {
return res.json()
})
.then((payload) => {
return payload
}).catch((error) => {
throw error
})