Axios VS Postman request get different responses - javascript

Hello guys I came across a strange issue I got with connection to an API.
While I am using Postman everything goes well but if I make the request with Axios the response is different. So to give you an example I want to get a client with id 616;
Client
await axios
.post("/api/getClient", {
id: 616,
}).then(data => console.log(data))
Backend
// GET CLIENT
app.post('/api/getClient', async (req, res) => {
const d = await axios.get(`${baseURL}/client/account/:client_id`, {
headers: headers,
data: {
id: req.body.id
}
})
res.send(d.data)
res.end()
});
Response from axios look like this
data: {
error: false,
user: {
profile: null,
user_addresses: [],
safe_credits: 0,
rating: 5
}
}
From Postman
{
"error": false,
"user": {
"profile": {
"id": 616,
"phone_number": "07744444444",
"country_code": "44",
"email": "email#example.com",
"first_name": "John",
"last_name": "Doe",
"password": null,
"os": "iOS",
"token": "0c9c09e7dc2f009b4cfdb2e4666ead9e",
"version": "",
"photo": "",
"gender": "male",
"registered_date": "2020-05-08T14:55:05.000Z",
"enabled": 1,
"socketId": "",
"stripe_id": "cus_HF1eUUdada54JKN"
},
"user_addresses": [],
"safe_credits": 0,
"rating": 5
}
}

Instead of using data in your request, you should just be able to append the ID to your API URL:
const d = await axios.get(`${baseURL}/client/account/${req.body.id}`, {
...
});

I had recently a similar issue.
In postman make sure you delete any cookies, as this might affect results.
Postman stores cookies between different requests on the same domain. While axios (or any other backend library) might not.
Under the "Send" button in postman, check the cookies, delete any cookies you find there and re-execute. This might give you the same result you're having in axios.

Related

Axios PUT request -React

I want to send a put request to modify the command part of my JSON file. Here is my JSON;
{
"users": [
{
"hostname": "xxx.xxx.xxx.xx",
"password": "password1",
"command": "command1",
"id": 1
},
{
"hostname": "xxx.xxx.xxx.xx",
"password": "password2",
"command": "command2",
"id": 2
},
{
"hostname": "xxx.xx.xx.xxx",
"password": "password3",
"command": "command3",
"id": 3
}
]
}
In App.js I send put request like this;
stopPC(id){
axios.put('http://localhost:3002/users/'+id,{
command: 'stop'
})
}
And I have tried this;
axios({
method: 'put',
url: 'http://localhost:3002/users/'+ id,
data: {
hostname: id.hostname,
password: id.password,
command: 'stop'
}
});
In both, I got the following output in the JSON file.
{
"users": [
{
"command": "stop",
"id": 1
},
{
"hostname": "xxx.xxx.xxx.xx",
"password": "password2",
"command": "command2",
"id": 2
},
{
"hostname": "xxx.xxx.xxx.xx",
"password": "password3",
"command": "command3",
"id": 3
}
]
}
I want to change only the command information while keeping the hostname and password information the same.
I'm not sure where I went wrong, I'd be glad if you could help.
If id is of type Number (which I think it is), id.hostname and id.password would be undefined, so basically
{
hostname: id.hostname,
password: id.password,
command: 'stop'
}
and
{
command: 'stop'
}
are the same to Javascript and you're effectively sending the same payload. I think that the best way of solving this would be changing how the backend handles the incoming payload by just changing the properties that came in the request. If you don't have access to changing the backend, you would have to get or read the current stored value and use that in the payload. Something like
user = axios.get('http://localhost:3002/users/'+id).then(r => r.data)
axios.put('http://localhost:3002/users/'+id,{
hostname: user.hostname,
password: user.password,
command: 'stop'
})
Also, PUT is meant to be used used to replace a record, and PATCH to update the existing one, which sounds more like what you want to do. Maybe just try axios.patch and it may work.
I did quite the same than #rodrigo-naranjo except I embedded the put call in the response of the get call:👇
axios.get("http://localhost:3002/users/" + id).then((r) => {
let user = r.data;
axios.put("http://localhost:3002/users/" + id, {
hostname: user.hostname,
password: user.password,
command: "stop",
});
});
with id an input value from your app context.

Unable to set JWT token as environment variable when user login/sign-up in postman using test script?

Unable to set JWT token as environment variable when user login/sign-up in postman set-up using test script. I am using below test script in postman. But that's not working
postman.setEnvironmentVariable("jwt", postman.response.json().token);
Below is my response
{
"status": "success",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVmNjViYjZiNzdkYmEyNDM5YzM2NGRiNSIsImlhdCI6MTYwMDUwMjYzNiwiZXhwIjoxNjA4Mjc4NjM2fQ.Pkhdghgdhc8jOVcIendST5YHHeKzX69CwP7F9KgI",
"data": {
"user": {
"_id": "5f65bb6b77dba2439c364db5",
"name": "vickram",
"email": "testuser#test.com",
"password": "$2a$12$TphQKpGCawxaNBJO8UpnIut2dSucCPGgdPt/1KFlO5EtBt7Yy4xUW",
"__v": 0
}
}
}
This will do it: pm.environment.set("jwt", pm.response.json().token);
You should do like this:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.token);

How to get JSON payload sent by the Slack action message?

I am trying to build a Slack bot with interactive buttons. I have set up a Google Apps Script to handle the action performed on the Slack message. I want the payload of the request sent by the Slack. I have tried to get the request object by doing
function doPost(e) {
return processComment(e);
}
function processComment(e) {
Logger.log(e);
}
{postData=FileUpload, queryString=method=slack, parameter={method=slack, payload={"type":"block_actions","user":{"id":"U01835Mxxxx","username":"ravsamteam","name":"ravsamteam","team_id":"T0160UQZZZZ"},"api_app_id":"A018MPZ2xxx","token":"NTNRCTPDz8mxxxzxxxxxxxxx","container":{"channel_id":"C0190D8L2AU","is_ephemeral":false,"message_ts":"1597154895.001500","type":"message"},"trigger_id":"1281039280903.1204976558018.aa1055f6900d7884d9cd4ac34ffzzzzz","team":{"id":"T0160UQGE0J","domain":"ravsamhq"},"channel":{"id":"C0190D8L2AU","name":"blogs"},"message":{"type":"message","subtype":"bot_message","text":"This content can't be displayed.","ts":"1597154895.001500","bot_id":"B019BNL08BS","blocks":[{"type":"section","block_id":"mNavk","text":{"type":"mrkdwn","text":" New comment on RavSam's blog by hello","verbatim":false}},{"type":"section","block_id":"v3Ip","text":{"type":"mrkdwn","text":"*Blog:*\nhello\n\n*Comment:*\nravgeet errorCannot read property 'payload' of undefined","verbatim":false}},{"type":"actions","block_id":"1maVO","elements":[{"type":"button","action_id":"WSo=","text":{"type":"plain_text","text":"Approve","emoji":true},"style":"primary","value":"approved"},{"type":"button","action_id":"Vek\/","text":{"type":"plain_text","text":"Deny","emoji":true},"style":"danger","value":"denied"}]}]},"response_url":"https:\/\/hooks.slack.com\/actions\/T0160Uxxxxx\/1301968xxxxxx\/Q3gZhbeUCUIxxxxxxxxxxxxx","actions":[{"action_id":"WSo=","block_id":"1maVO","text":{"type":"plain_text","text":"Approve","emoji":true},"type":"button","value":"approved","action_ts":"1597213837.152704"}]}}, contentLength=2391.0, parameters={payload=[Ljava.lang.Object;#53f2e9fa, method=[Ljava.lang.Object;#5793298b}, contextPath=}
How do I get the payload? Once I have the payload JSON, I can use the actions to determine what action was taken by the user?
Yes. The payload contains all the information you need to identify the action. And it also contains a response_url to respond back.
Slack payload should look like this.
{
"actions": [
{
"name": "channels_list",
"selected_options": [
{
"value": "C012AB3CD"
}
]
}
],
"callback_id": "select_simple_1234",
"team": {
"id": "T012AB0A1",
"domain": "pocket-calculator"
},
"channel": {
"id": "C012AB3CD",
"name": "general"
},
"user": {
"id": "U012A1BCD",
"name": "musik"
},
"action_ts": "1481579588.685999",
"message_ts": "1481579582.000003",
"attachment_id": "1",
"token": "iUeRJkkRC9RMMvSRTd8gdq2m",
"response_url": "https://hooks.slack.com/actions/T012AB0A1/123456789/JpmK0yzoZDeRiqfeduTBYXWQ",
"trigger_id": "13345224609.738474920.8088930838d88f008e0"
}
You can learn more here.

basic auth axios - klarna checkout

I am implementing Klarna Checkout in my webapp. Backend using aws serverless. Frontend: react.
I am stucked at creating a order. It works fine inside postman but I can't get basic auth working axios.
For testing purposes I am posting orders from my react app. It will be moved to the backend once I get it working.
My axios code looks like this.
axios
.post(
"https://api.playground.klarna.com/checkout/v3/orders",
{
purchase_country: "DE",
purchase_currency: "EUR",
locale: "de-DE",
order_amount: 3,
order_tax_amount: 0,
order_lines: [
{
type: "digital",
reference: "Test",
name: "Test Subscription",
quantity: 1,
quantity_unit: "pcs",
unit_price: 3,
tax_rate: 0,
total_amount: 3,
total_discount_amount: 0,
total_tax_amount: 0
}
],
merchant_urls: {
terms: "https://www.example.com/terms.html",
checkout: "https://www.example.com/checkout.html",
confirmation: "https://www.example.com/confirmation.html",
push: "https://www.example.com/api/push"
}
},
{
auth: {
username: "xxx",
password: "xxx"
},
headers: {
"Content-Type": "application/json"
}
}
)
.then(result => console.dir(result));
I get a 401 error at OPTIONS.
The response I'm getting.
I have tried it with postman, which works fine.
To summarize the comments: Klarna's API cannot be called from browser only from serverside.
I called the same code from my aws lambda and it worked fine.

JAVASCRIPT editing headers to call api that returns json

I am trying to use an API that is hosted externally and also returns JSON data. I have tried editing the headers but I'm not entirely sure it is working because I am still getting a warning about not having the CORS header
Source
var url = "http://hkconsult.in/social_search/keyword_services.php?keyword=throat&callback=test";
$.ajax({
type: 'get',
url: url,
headers: {
"Origin":"http://hkconsult.in/social_search/keyword_services.php?keyword=throat&callback=test",
"Access-Control-Allow-Origin":"http://hkconsult.in/social_search/keyword_services.php?keyword=throat&callback=test"
}
}).done(function(data) {
document.getElementById('cool').innerHTML = data;
});
Firebug Headers
When opening the response for the "OPTIONS" url in firebug, it returns the data that I want. How do I use that data in javascript?
The CORS are headers that the server should send you as a response to your request.
The OPTIONS request is performed by the browser to check those headers prior to performing your actual request.
You cannot get the result of that OPTIONS request because it happens outside the scope of your code.
If the server is not setup to send those headers, then your only option is to use a proxy page that will use a server-side script to perform the call on your behalf.
As per my understanding you are asking about how to parse the response JSON instead of CORS Issue.
var data = {
"0": {
"keyword_name": "Sore throat",
"id": "1787",
"user_id": "3350988339",
"user_name": "Nic",
"user_screen_name": "Goldendevi",
"user_profile_pic": "http://pbs.twimg.com/profile_images/840766770633945088/eRRoRZHv_normal.jpg",
"user_location": "",
"post_id": "864553159896838145",
"post_text": "I'm so mad I have a fucking sore throat 🙄",
"post_geo_location": "0",
"post_image": "",
"post_date": "2017-05-16 20:48:30"
},
"1": {
"keyword_name": "Sore throat",
"id": "1788",
"user_id": "63496454",
"user_name": "mariana",
"user_screen_name": "yugyeumie",
"user_profile_pic": "http://pbs.twimg.com/profile_images/863802594132733952/ep0DtSoT_normal.jpg",
"user_location": "jjp; 맠슨",
"post_id": "864552988974747649",
"post_text": "is it possible to die of a sore throat",
"post_geo_location": "0",
"post_image": "",
"post_date": "2017-05-16 20:47:49"
}
};
var res = Object.keys(data).map(item => {return data[item].keyword_name });
console.log(res);

Categories

Resources