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);
});
Related
the request getting to the server without the headers:
const res = await axios.post(`/api/follow/${props.match.url}`, {
headers: {
Authorization: `Bearer ${token}`,
userId: userId,
},
});
anyone knows why?
should just put null in the body place, and it works
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'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"));
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
})
I am struggling to get a C# WebAPI auth token using react. I have a Postman request that works correctly; it gives me my token as expected:
I have tried recreating this request using both Axios and Fetch. The requests were as follows:
Attempt 1:
fetch('http://localhost:56765/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: JSON.stringify({ username: 'test#test.com', password: 'Test123!', grant_type: 'password' })
})
Attempt 2:
axios('http://localhost:56765/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: JSON.stringify({ username: 'test#test.com', password: 'Test123!', grant_type: 'password' })
})
Attempt 3:
const data = JSON.stringify({ username: 'test#test.com', password: 'Test123!', grant_type: 'password' });
const headers = { 'Content-Type': 'application/x-www-form-urlencoded', };
axios.post('http://localhost:56765/token', data, { headers })
When I make the request, the response is:
400 Bad Request
{"error":"unsupported_grant_type"}
Picture example:
Does anyone know where I am going wrong?
Edit:
The code that worked for me was installing qs then:
var qs = require('qs');
const data = qs.stringify({ username: 'test#test.com', password: 'Test123!', grant_type: 'password' });
axios.post('http://localhost:56765/token', data)
I was able to completely omit the header.
Many thanks to Brub for answering on Xmas day!
You are passing content-type of application/x-www-form-urlencoded but the actual form data of type application/json. You want to post the data as form-urlencoded described here:
https://github.com/axios/axios/issues/350#issuecomment-227270046
Note the Oauth 2.0 spec requires application/x-www-form-urlencoded
https://www.rfc-editor.org/rfc/rfc6749#section-4.3.2