I have a API call that takes a POST body of
raw: {"category":1, "fmipstatus":true} and it is of type JSON.
Content-Type is application/json
I use Postman to send this API call and I get a 200 response code.
I want to code this call as part of a Postman Pre-request Script
I have the following:
method: 'POST',
header: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Basic NDc0OmVmMzAwZThkNGFjNTQ2ZjU3ZjhjYWQ5ZWQwMjUyNGIxYTI5NmQwM2M='
},
body: {
mode: 'raw',
raw: JSON.stringify( {category: 1, fmipstatus: false} )
}
I always a 401. In the first API through Postman, if I put garbage in there, I also get a 401 response code.
So I am thinking somehow in my Postman script, the body is defined incorrectly.
Does anyone the error?
401 is an authorization error. Something is wrong with your Auth token, either its expired, incorrect, or you're passing it incorrectly.
Related
I configured Postman to use the authorization code flow. Problem is our tokens expiry pretty fast and I need to re-run the flow every time it expires. So I was thinking to implement a refresh_token flow in the pre-requests script (unless there is a Postman-native way to do it).
Now my question is where can I find the refresh_token? Is there any way to access it or is it 'thrown away' and only the access_token is used?
Add the following code to the Collection Pre-request Script. (Edit it to your own url and body.)
// Set refresh and access tokens
const loginRequest = {
url: pm.environment.get("mainUrl") + "/authenticate/login", //The url that the token returns
method: 'POST',
header: {
'content-type': 'application/json',
'Accept': "*/*"
},
body: {
mode: 'raw',
raw: JSON.stringify({ //Your body
"username": pm.environment.get("username"),
"password": pm.environment.get("password")
})
}
};
pm.sendRequest(loginRequest, function (err, res) {
pm.environment.set("accessToken", res.json().accessToken); //The token returned in the response and the environment value to which the value will be sent
pm.environment.set("refreshToken", res.json().refreshToken);
});
This request runs before every request.
Finally, In the "Token" field in the "Authorization" tab of the requests, call the accessToken value from the environments.
{{accessToken}}
Each time the request runs, it will refresh the token value and use this value.
In my Postman collection, I have a pre-request script that ensures I have a valid JWT token available for authentication. It looks similar to the following (I have removed the logic of checking expiration and only fetching a new token if needed):
function get_and_set_jwt() {
let base_url = pm.environment.get("BASE_URL")
pm.sendRequest({
url: base_url + '/api/auth/',
method: 'POST',
header: {
'content-type': 'application/json',
'cookie': ''
},
body: {
mode: 'raw',
raw: JSON.stringify({ email: pm.environment.get("USER_EMAIL_ADDRESS"), password: pm.environment.get("USER_PASSWORD") })
}
}, function (err, res) {
let jwt = res.json().token
postman.setEnvironmentVariable("JWT", jwt)
});
}
get_and_set_jwt();
I am attempting to set 'cookie': '' so that the request from this script will be made with no cookies. The backend I am working with sets a session cookie in addition to returning the JWT, but I want to force all future requests (when I need to renew the JWT) to not include that session information.
Unfortunately, if I check the Postman console, I see that the requests are still being sent with the cookie header, and the session cookie that was set by the earlier response. I have even tried overriding it by setting 'cookie': 'sessionid=""', but that just yields a request that includes two session ids in the cookie header (it looks like sessionid=""; sessionid=fasdflkjawew123sdf123;)
How can I send a request with pm.sendRequest with either a completely blank cookie header, or without the header at all?
I am using Token authentication for Django & React integration.
The below POST method fails in React with status 401,however same method give status 200 ok from POSTMAN(with same token,url and id)
axios
.post(`songs/${id}/like`, {
headers: { Authorization: `Token ${token}` }})
.then()
.catch();
};
I have ensured that I passed all parameters to axios but something got wrong.
Other interaction with backends like login,signup,GET methods work fine.
What are the possible causes for the error ?
I have set CORSORIGINALLOWALL=True.
I think second param should be data for axios.post try the below snippet:
axios.post(`songs/${id}/like`, {} , { headers: { Authorization: `Token ${token}` }})
I'm trying to POST data from my React app to Django REST API by fetch method like this:
fetch('http://127.0.0.1:8000/something/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
mode: 'no-cors',
body: JSON.stringify(this.state)
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
I always get an error "POST http://127.0.0.1:8000/something/ net::ERR_ABORTED 415 (Unsupported Media Type)" and the response looks like this: "Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}".
My state contains only empty strings (username: '', password: '' etc.)
I've also tried to send a GET request using axios and print a response in a console:
axios.get('http://127.0.0.1:8000/something/')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error)
})
But the response is:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/something/' from origin
'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
header is present on the requested resource.
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
GET http://127.0.0.1:8000/something/ net::ERR_FAILED
Have you got any ideas to fix that problem?
You are getting this issue in the GET request due to CORS restriction, which is a default browser restriction that prevents fetching data from external APIs.
You can do the following:
If you are using Google Chrome, add this extension-https://chrome.google.com/webstore/detail/who-cors/hnlimanpjeeomjnpdglldcnpkppmndbp?hl=en-GB.
Reload the browser tab(s).
Regarding the error 415 you are receiving during POST request, it is because of header mismatch, since you have used 'no-cors' as your mode, your request headers become immutable, thus even if you are passing 'Content-Type' as 'application/json', it gets passed as 'text/char', because of this mismatch 415 error is thrown. You can contact the backend team and ask them to change the 'Content-Type' as 'text/char', it should work for you.
I can send a request in a Postman pre-request script as seen below. What I would like to do is use the same authentication as is set in the Collection so that if the Collection changes then my sendRequest follows suite.
pm.sendRequest({
url: 'http://some_url',
method: 'GET',
header: {
'content-type': 'application/json',
'authorization': 'Basic ' + auth
},
}, function (err, res) {
// do something
});
The reason I want to do this is that I want to share the collection with partners and customers and each of them may use a different authentication type. At the moment I have configured my collection to use basic authentication and have used variables for user name and password. If, for example, a partner switches the collection to use OAuth then they will need to also update all of my pre-request scripts to use OAuth.
If pm.sendRequest() was able to inherit the authentication just as each request in the collection can then the partner could make the change in one place.
This will work, assuming you're executing sendRequest after a request which had an authorization header as well:
pm.sendRequest({
url: 'http://some_url',
method: 'GET',
header: {
'content-type': 'application/json',
'authorization': request.headers["authorization"]
},
}, function (err, res) {
// do something
});
Information on the Request object can be found here.