Axios PUT request -React - javascript

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.

Related

unable to perform CRUD in JSON-SERVER

I am trying to add, update, delete in JSON server with Redux Axios. But I am unable to perform CRUD action. I am always getting an error 404. I am using the following code example. this my db.json
{
"orderdetails": [
{
"OrderID": 111,
"CustomerID": "VINET",
}
]
}
I am using the following code for importing Axios from redux. Please find my server.js
import axios from 'axios';
export default axios.create({
baseURL: "http://localhost:3007/",
headers: {
"Content-type": "application/json"
}
})
I am using the following code example for performing CRUD action in the JSON-Sever. But, I am got a error
import http from "../serverapi";
create(data) {
return http.post("/orderdetails/posts", data);
}
update(id, data) {
return http.put(`/orderdetails/${id}`, data);
}
delete(id) {
return http.delete(`/orderdetails/${id}`);
}
could you please provide the suggestion?
If you are using the json-server npm package, there are a couple of problems with your usage.
First, you db.json is invalid. It should be somewhat like this:
{
"orderdetails": [
{
"OrderID": 111,
"CustomerID": "VINET"
},
{
"OrderID": 12,
"CustomerID": "VINET"
}
]
}
Make sure to check the API url in the browser first.
Second, json-server by default runs on localhost:3000 (Not sure if it can be changed, check the docs here https://www.npmjs.com/package/json-server). Your API is pointing to port 3007 as seen here baseURL: "http://localhost:3007/,
Lastly, you cannot do a request like http://localhost:3000/orderdetails/111. The last part in the api url by default corresponds to the id key in db.json, but since your key is OrderID, your API end point should be modified to http://localhost:3000/orderdetails?OrderID=111. Try this url in your browser, it should return the correct object.
UPDATE
Update operations in json-server require the id key to be present in the db.json file. Hence, update your db.json as follows:
{
"orderdetails": [
{
"id": 1,
"OrderID": 111,
"CustomerID": "VINET"
},
{
"id": 2,
"OrderID": 12,
"CustomerID": "VINET"
}
]
}
Then, you can try running a POST request on the url http://localhost:3000/orderdetails and json body :
{
"OrderID": 12333,
"CustomerID": "VINET"
}
This will create a new object in the db, with incremented id. PUT, DELETE requests can be made using the id param in the url like http://localhost:3000/orderdetails/3.

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.

Axios VS Postman request get different responses

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.

Parse push notification shows empty geo-queries

This is similar to but it's a continuation to Parse geo-queries always empty
I have device installations working correctly, and i've created a customized class "test_users" that contains the location data. each instance in the "Installation" class holds a pointer to the "test_users" instance, with column name "test" below** you can see below, and when I clicked on the pointer value, it will go to that "test_user" instance.
and "test_users" class
I have the following javascript code to Query the channel and location to send push notification:
$http({
"url": "https://api.parse.com/1/push",
"method": "POST",
"data": {
"data": { "alert": "test!! ",
"sound": "beep.caf",
"badge": "Increment",
"uid":user_uid,
"date":date,
"time":time
},
"where": {
"channel": category,
"test": {
"$inQuery": {
"location": {
"$nearSphere": {
"__type": "GeoPoint",
"latitude": 37.7150 ,
"longitude": -117.1625
},
"$maxDistanceInMiles": 20
}
}
}
}
},
"headers": {
"X-Parse-Application-Id": "######",
"X-Parse-REST-API-Key": "#######",
"Content-Type": "application/json"
},
"params":
{
"uid" : user_uid,
"date": date,
"time": time
}
});
However, no push notification is created, and when i check the analytics, i see this
Any thoughts on where I made the query mistake? or anything wrong with "test_users" class? Update: On a different experiment, I also created a _User class just like the parse.com push notification doc did (and have "Installation" instance storing a pointer to the _User instance), and got same empty geo-query result.

how to check if database needs auth or not

I'm working on a project which allows user to login to a mongodb database. Basically I have
db.authenticate(username, password, function(err, isAuthPass) {...}
to check if the user pass the authentication. However, sometimes the server doesn't need authentication. If I provide username/password, it will fail. So I need to know how to check auth mode with mongo-native-client. Any idea?
Well I suppose you could just interrogate the database for the config information. This does come with the caveat that you should also be using the "test/fail" methods as discussed before as you would not be able to get this information from a server with authentication enabled that is not running on localhost:
var mongo = require('mongodb'),
MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://localhost:30000/test',function(err,db) {
var adminDb = db.admin();
adminDb.command({ "getCmdLineOpts": 1 },function(err,result) {
console.log( JSON.stringify( result, undefined, 4 ) );
});
});
That shows the "parsed" options, and it does not matter whether they are actually sent from the command line or picked up from a config file as the output here suggests:
{
"documents": [
{
"argv": [
"mongod",
"--config",
"mongod.conf"
],
"parsed": {
"config": "mongod.conf",
"net": {
"bindIp": "0.0.0.0",
"port": 30000
},
"security": {
"authorization": "enabled"
},
"storage": {
"dbPath": "data"
},
"systemLog": {
"destination": "file",
"logAppend": true,
"path": "log/mongod.log"
}
},
"ok": 1
}
],
"index": 338,
"messageLength": 338,
"requestId": 25,
"responseTo": 3,
"responseFlag": 8,
"cursorId": "0",
"startingFrom": 0,
"numberReturned": 1
}
So here the presence of "security.authorization.enabled": true tells you that further operations are going to require authorized credentials to be supplied.
Also see getCmdLineOpts and other diagnostic information commands that should be useful for your tool.
Sometimes? always use a password. and if you don't need one, like your local environment, you should use a config file for that environment like ./config/dev.js which has the credentials for that environment.

Categories

Resources