POSTMAN not sending anything in the body in POST requests - postman

I am trying to test the /login API via POSTMAN (via FE it works fine) but it doesn't
show anything in the body part even though I am sending body data.
but when printing the request from the BE, the body is empty...
....
body: {},
....
unlike when using FE:
....
body: {data: { username: 'admin', password: 'admin' }},
....
Any idea what's going on? If anything else is needed to be provided - pls let me know
I know it's going through because the server responds with 500 and the message
TypeError: Cannot read property 'username' of undefined
The weird part is, that the data I am sending, are nowhere to be found in the request object at all :(
EDIT:
This is how I call it from the FE:
return axios.post('login', { data: user })
and the user is:
user: {
username: 'admin',
password: 'admin'
}
So the format should be right
data: {
username: 'admin',
password: 'admin'
}
Because that's how I access it on the BE side
req.body.data.username
EDIT2:
The ultra-super-rare-weird part is, that JEST is working fine :)
const creds = {
data: {
username: 'admin',
password: 'admin'
}
}
return request(app)
.post("/api/v1/login")
.send(creds)
.expect(200)
.then(res => {
expect(res.body).toMatchSnapshot()
})
and this test passes .... f**k me guys.. what's going on?

if you are working with an express server try to parse your body in the server as soon as you initialize express app before routing
const app = express();
app.use(express.json());

The syntax of your body looks like JSON, yet you've specified the type of the body as "raw text". This will set the Content-type header of your request to "text/plain", which is probably causing your backend to be unable to actually read the body (because it expects a JSON object).
Simply switch from "Text" to "JSON", wrap your current body in curly braces (so that you're actually sending a single JSON object with a data property set) and try sending the request again. The content-type header will be correctly set to "application/json" this time and your backend will read the data successfully.

Add the following parameters in the request headers configuration in Postman:
Content-Type: application/json
Content-Length
The value of Content-Length is automatically calculated by Postman when a request is sent. Both values are used to identify the media type of the request body and to parse it accurately. When missing, the body may be ignored completely (depending on the server).

Related

I am using htmx javascript API how do I get the response from server

My code block looks like this, basically when a modal is triggered I send a GET request and retrieve the response, it does send the request alright, but I am unable to see (or to put it better) to get the response from the server via .then() from htmx. I am using the example from there documentation.
htmx.ajax('GET',
'/user-related-comment/',
{ swap: 'none', values: { userId: userId } }
).then(data => {
console.log(data)
})
data is undefined when logged to browser console.
For anyone that needs to do this, an option will be to listen to 'htmx:afterOnLoad' event example.
htmx.ajax('GET', '/example', '#myDiv').then(() => {
document.body.addEventListener('htmx:afterOnLoad', event=>{
console.log(event)
// access response at event.detail.xhr.response
// convert to JavaScript object by JSON.parse(event.detail.xhr.response)
})
});
For some reason on first click, does nothing.

Request body is not being passed from axios get call to Django Rest Framework

I have an issue while sending get request with a body in axios. It does not pass the body of the request to the backend.
Axios code looks like below
const FunctionName = (environment, page_num) => {
axios.get(API_URL,
{ params:
{
environment,
page_num
},
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err.response.data);
});
}
I'm using Django as my backend and I'm receiving empty body i.e {} which causes bad request sent to the backend. I went through several stack overflow questions but none of them helped me. Can anyone please help me with this.
Update
My django code looks like below
class TestView(APIView);
def get(self, request):
environment = request.data['environment']
page_num = request.data['page_num']
...
...
Here when I'm unable to get the environment or page_num data. The same request when I send from postman with the get call and content in the request of the body, it accepts and sends the response back.
Re-Update
I noticed that we have to use request.query_params['some_val'] incase we're passing the body in a request from Axios but request.query_params['some_val'] will not work if we send a request with the body in postman. I'm not sure it is normal behavior or not!
I'm not sure but try this:
axios({
method: "get",
url: API_URL,
body: {
environment,
page_num
}
}).then(res => console.log(res.data));
In Django, are you try get body with request.body
Anyone who's facing the issue can find the answer below to the link.
Possible duplicate
How to access get request data in django rest framework

Postman - Using complete response from one request as body of another request

I have a request were the exact response from one request is the body of another request.
Is there an easy way to store the response from one request to reuse as the body of another request in Postman?
I tried storing the response body in a global variable customerData and then having the body of my other request be {{customerData}} but this does not work.
Thanks for the help.
You could achieve this by using the sendRequest() function in the Tests tab of your first GET request. This will send the request and get the data once this has completed, it will then POST that same response data to another endpoint.
This is a very basic example that can be added to the Tests tab, this can be changed/adapted to your own context:
pm.sendRequest({
url: 'localhost:3000/post',
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify(pm.response.json())
}
}, (err, res) => {
console.log(res)
})
This is what it looks like in Postman - I've sent a basic request to the /get route and in the Tests tab, I'm using that response data as the payload for the POST request by inserting the pm.response.json(). You can see the request body for the /post route has been taken from the first request.
API-1 - Test Tab
//Get the response of first API
var jsonData=JSON.parse(responseBody);
//Convert the JSON response to String
var jsonString=JSON.stringify(jsonData);
//Store in environment variable
pm.environment.set("MyPayLoad", jsonString);
API-2 - Body
{{MyPayLoad}}
This way response from API-1 is passed as payload to API-2

ember-cli-mirage error: Nothing returned by handler, but handler exists

In the app I'm working with, we have a GET route that validates a user's email address. If the email is invalid, the server responds with:
a 200 status code
response headers with Content-Type:application/json; charset=utf-8
and the response data itself is just a string of "This email is invalid"
I'm trying to simulate this in ember-cli-mirage by doing:
this.get('/ember_api/v1/validations/validate_email', function() {
return [200, { 'Content-Type': 'application/json' }, "This email is invalid"];
// also tried this:
// return new Mirage.Response(200, { 'Content-Type': 'application/json' }, JSON.stringify({"message":"This email is invalid"}));
// and tried this:
// return "This email is invalid";
});
The test itself is a button click that fires off this request:
GET "/ember_api/v1/validations/validate_email?email=fakey%40fakefakefake.com&skip_uniq=true"
...and the error I'm getting is:
Pretender intercepted GET /ember_api/v1/validations/validate_email?email=tom%40gmail.com&skip_uniq=true but encountered an error: Nothing returned by handler for /ember_api/v1/validations/validate_email?email=tom%40gmail.com&skip_uniq=true. Remember to return [status, headers, body]; in your route handler.`
It's asking me to return [status, headers, body], but I'm doing this in my handler, and it still throws the error.
Is this actually an issue with the response? Do I need to edit my API to actually return a JSON API formatted object, so I can write the test that way?
I feel like I should be able to return a string in my test since that's what the app is doing. Any help is appreciated.
The this.get you are using is the Mirage version. You can also use this.pretender.get which should work with your current code sample ...

AngularJS POST JSON to Django REST API

I am building an app with AngularJS and using external API made with Django.
For API calls I'm using Restangular (but it's not the case because even with $http I get the same).
My default content-type for post calls is:
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
This is done just so I could send credentials when signing in win OAuth2:
var data = {
grant_type: 'password',
client_id: clientID,
client_secret: clientSecret,
username: username,
password: password
};
$http.post('http://server.com/api/oauth2/access_token/', data);
GET is done using default AngularJS configuration (application/json I guess).
So far so good, everything was working until... I was making POST requests and sending large JSON objects.
The configuration from above didn't work, so I changed those POST requests to application/json, and getting error response:
400: JSON parse error - No JSON object could be decoded
Tried the same with just jQuery - and it worked although I had to do JSON.strigify and in error debugging on Chrome Request Payload with jQuery looks like a proper object, and with AngularJS looks like this:
type=Feature&geometry=%5Bobject%20Object%5D&properties=%5Bobject%20Object%5D
(yes, by the way, I'm sending a valid GeoJSON object)
So I thought maybe JSON.stringify has something to do with this but after applying this to my object, the Request Payload from AngularJS is a mess:
0=%7B&1=%22&2=t&3=y&4=p&5=e&6=%22&7=%3A&8=%22&9=F&10=e&11=a&12=t&13=u&14=r&15=e&16=%22&17=%2C&18=%22&19=g&20=e&21=o&22=m&23=e&24=t&25=r&26=y&27=%22&28=%3A&29=%7B&30=%22&31=t&32=y&33=p&34=e&35=%22&36=%3A&37=%22&38=P&39=o&40=i&41=n&42=t&43=%22&44=%2C&45=%22&46=c&47=o&48=o&49=r&50=d&51=i&52=n&53=a&54=t&55=e&56=s&57=%22&58=%3A&59=%5B&60=1&61=9&62=.&63=0&64=8&65=3&66=2&67=4&68=1&69=2&70=2&71=4&72=2&73=8&74=8&75=9&76=%2C&77=5&78=0&79=.&80=2&81=4&82=2&83=4&84=0&85=2&86=0&87=7&88=2&89=3&90=6&91=8&92=9&93=%5D&94=%7D&95=%2C&96=%22&97=p&98=r&99=o&100=p&101=e&102=r&103=t&104=i&105=e&106=s&107=%22&108=%3A&109=%7B&110=%22&111=c&112=o&113=n&114=t&115=r&116=i&117=b&118=u&119=t&120=i&121=o&122=n&123=t&124=y&125=p&126=e&127=%22&128=%3A&129=1&130=2&131=1&132=4&133=5&134=%2C&135=%22&136=l&137=o&138=c&139=a&140=t&141=i&142=o&143=n&144=%22&145=%3A&146=%7B&147=%22&148=n&149=a&150=m&151=e&152=%22&153=%3A&154=%22&155=D&156=a&157=n&158='&159=s&160=%20&161=H&162=o&163=u&164=s&165=e&166=%22&167=%2C&168=%22&169=d&170=e&171=s&172=c&173=r&174=i&175=p&176=t&177=i&178=o&179=n&180=%22&181=%3A&182=n&183=u&184=l&185=l&186=%2C&187=%22&188=s&189=t&190=a&191=t&192=u&193=s&194=%22&195=%3A&196=n&197=u&198=l&199=l&200=%2C&201=%22&202=c&203=r&204=e&205=a&206=t&207=e&208=d&209=_&210=a&211=t&212=%22&213=%3A&214=%22&215=2&216=0&217=1&218=4&219=-&220=0&221=4&222=-&223=3&224=0&225=T&226=1&227=0&228=%3A&229=2&230=4&231=%3A&232=5&233=8&234=.&235=9&236=3&237=7&238=Z&239=%22&240=%2C&241=%22&242=i&243=d&244=%22&245=%3A&246=4&247=5&248=%7D&249=%7D&250=%7D
Any help? What I'm doing wrong? Or it has something to do with Django API? Should we change something in it?
SOLVED
The problem was caused by serialiser (my interpretation of jQuery's $.param). Apparently I needed this for sending credentials for the OAuth2 but not for any other POST request.
Although I still don't know why it is like that.
try this
var data = {
grant_type: 'password',
client_id: clientID,
client_secret: clientSecret,
username: username,
password: password
};
$http.post('http://server.com/api/oauth2/access_token/', angular.toJson(data));
Include jquery and try this
$http({
method: 'POST',
url: 'http://server.com/api/oauth2/access_token/',
data: $.param(data)
});