How to code a javascript JSON RPC from scratch, problem with the response - rpc

I'm trying to code a json rpc from scratch. I tried using a fetch, but what the server returns is not the information I want. I believe I need to stay connected waiting for a return from the server. My purpose is to make a request to ganache and get a response. From the ganache log I see that he received the request, but I don't know how to get his return. My initial code was as follows.
const nodeFetch = require('node-fetch')
async function run() {
const retorno = await nodeFetch('HTTP://127.0.0.1:7545', {
method: 'POST',
body: JSON.stringify({
"jsonrpc": "2.0",
"method": "eth_accounts",
"params": [],
"id": 1
}),
headers: {
'Content-Type':'application/json'
}
})
console.log(retorno)}
run();
The answer I get is
Thx

Related

How can I send a picture with the Discord API and express JS Requests

I have a problem that I would like to use the Discord API to upload an image. I send the image on the FrontEnd, then the BackEnd receives the image data. However, I don't know what I should write in the body to accept my photo upload request.
req.files.author is the file itself, which is of type "File".
If anyone could help me with this, I would greatly appreciate it.
code:
app.post("/api/sendEmbedMessage", async (req: any, res: Response) => {
console.log(req.files.author);
const serverRes = await fetch(`https://discord.com/api/v9/channels/1024734922134540370/messages`, {
method: 'post',
headers: {
'authorization': `${cfg.token}`,
// "Content-Disposition": `form-data; name="${req.files.author}"; filename="${req.files.author.name}"`,
"Content-Type": `application/json`
},
body: JSON.stringify({
"content":"képfeltöltés teszt",
"attachments": [
{
'id': 0,
"data": req.files.author
}
]
})
});
let respn = await serverRes.json()
console.log(respn.errors);
res.status(200).send(respn)
});
File Response:

http POST request works in VSCode testing, but doesn't work with node-fetch in lambda function

I have a lambda function that moderates input before calling the openai API. It works perfectly in sam local, as well as directly in VSCode (not through my lambda url). When I use my lambda function, I get this error:
{
"error": {
"code": null,
"param": null,
"message": "'input' is a required property",
"type": "invalid_request_error"
}
}
Here is the function that works locally (using SAM CLI invoke)
const moderationResponse = await fetch('https://api.openai.com/v1/moderations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `[PRIVATE]`
},
/* body is stringified before this step
and looks like { input: inputText }
*/
body: moderationBody
})
I'm not really getting any worthwhile logs to try to fix anything.

Somebody knows how to solve 401 Unauthorized error with Clockify API using axios and node js

Does someone know why I'm getting a 401 Unauthorized error when I try to post a request to add a time entry even though I have added my API key?
I'm using Axios and node js, and this is the information and how I am making the request. However, I am able to get a list of users using the axios.get() method with the same API key, so I'm not sure why the post request says I'm not Unauthorized.
const insertOwnTimeEntryUrl = `${url}/workspaces/${workspaceId}/time-entries`;
let payload = {
start: "2022-05-05T17:10:00.000Z",
billable: "true",
description: "Test insert 1",
projectId: projectIdToInsert,
taskId: taskIdToInsert,
end: "",
tagIds: [tagIdToInsert],
};
let headers = {
"X-Api-Key": key,
};
let clockifyData = {
headers,
payload,
};
async function addNewEntry(clockifyData, insertOwnTimeEntryUrl, key) {
return (response = await axios
.post(`${insertOwnTimeEntryUrl}`, {
data: clockifyData.payload,
headers: {
"X-Api-Key": key,
"Content-Type": "application/json",
},
})
.catch(function (error) {
console.log(error.response.data.message);
return;
}));
}
addNewEntry(clockifyData, insertOwnTimeEntryUrl, key);

Getting "EHOSTUNREACH" when trying to connect to API using Axios + Express.js

I started playing around with the Philips Hue Bridge API by sending it requests using Postman. I was able to authenticate myself, create a user and even successfully turn lights on or off.
Conclusion: I am able to reach the API.
Next I made a mini test javascript file to do the exact same using Node.js and axios#0.21.4. When I try the following code everything works and I receive the expected JSON responses:
const axios = require('axios')
axios({
method: 'GET',
url: 'http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T'
})
.then(({data}) => {
console.log('------> AXIOS RES: ', data)
})
.catch((err) => {
console.log('------> AXIOS ERR: ', err)
})
Conclusion: Axios is able to communicate with the API.
Next I wanted to build this into an Express.js endpoint. However when I try to use the same code inside of express#4.17.1 I get an error:
router.route('/getlights').get((req, res) => {
axios({
method: 'GET',
url: 'http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T/lights'
})
.then(({data}) => {
console.log('------> AXIOS RES: ', data)
res.json({
state: 'SUCCESS',
data
})
})
.catch((err) => {
console.log('------> AXIOS ERR: ', err)
res.json({
state: 'ERROR',
err
})
})
})
Response:
{
"state": "ERROR",
"err": {
"message": "connect EHOSTUNREACH 192.168.0.107:80",
"name": "Error",
"stack": "Error: connect EHOSTUNREACH 192.168.0.107:80\n at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16)",
"config": {
"url": "http://philips-hue.local/api/BYLCIlxABzz2eDHAxx70T/lights",
"method": "get",
"headers": {
"Accept": "application/json, text/plain, */*",
"User-Agent": "axios/0.21.1"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
},
"code": "EHOSTUNREACH"
}
}
I started troubleshooting the problem by first trying to changing the URL to a random online place holder like http://jsonplaceholder.typicode.com/posts/1 just to see if I could establish any connection at all. This actually worked right away.
This is where I got really confused. Why am I able to successfully communicate with the bridge using Postman or Axios in a javascript file, but NOT able to connect with it when the same Axios code is used by express. The problems seems to occur only when using both axios and express to connect to the bridge API.
I have already tried retesting this with node-fetch and 3 other versions of Axios. All tests failed the exact same way. The code by itself can always connect to the API but once the code is being called by express it causes the EHOSTUNREACH error.
I ran out of ideas on how to further google this issue since I am not sure what exactly is causing the problem (express and/or axios and/or bridge). Any trouble shooting ideas or google keywords are also very welcome. :)
I had the same error, for some reason the ip address of my hue bridge had changed so I went into the hue app on my smartphone and copied the new ip address. IDK if this is helpfull, im pretty new here.
I had the same error since yesterday, and couldn't find solution. What actually caused mine was, there was a bearer token on the 3rd party api I called and i also pass it through the header as well.
So it was removed and pass the token through header and it works fine.
UPDATE: error keeps showing up if send another request.
The solution i found was to use request.
const request = require('request');
const headers = {
'Content-Type': 'application/json',
'token': `${token}`
};
const data = {
username : 'username'
}
let options = {
method: 'POST',
url: 'url',
port: 443,
headers: headers,
body: data,
json: true
};
request(options, async (error, res, body) => {
if (error) {
console.log({error});
return response.status(500).json({
status: false,
message: "Error occured"
});
} else {
console.log({body});
return response.status(201).json({
message: "success"
});
}
});

Node JS upload file streams over HTTP

I'm switching one of my projects from request over to something a bit more light-weight (such as got, axios, or fetch). Everything is going smoothly, however, I'm having an issue when attempting to upload a file stream (PUT and POST). It works fine with the request package, but any of the other three return a 500 from the server.
I know that a 500 generally means an issue on the server's end, but it is consistent only with the HTTP packages that I'm testing out. When I revert my code to use request, it works fine.
Here is my current Request code:
Request.put(`http://endpoint.com`, {
headers: {
Authorization: `Bearer ${account.token.access_token}`
},
formData: {
content: fs.createReadStream(localPath)
}
}, (err, response, body) => {
if (err) {
return callback(err);
}
return callback(null, body);
});
And here is one of the attempts using another package (in this case, got):
got.put(`http://endpoint.com`, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${account.token.access_token}`,
},
body: {
content: fs.createReadStream(localPath)
}
})
.then(response => {
return callback(null, response.body);
})
.catch(err => {
return callback(err);
});
Per the got documentation, I've also tried using the form-data package in conjunction with it according to its example and I still get the same issue.
The only difference between these 2 I can gather is with got I do have to manually specify the Content-Type header otherwise the endpoint does give me a proper error on that. Otherwise, I'm not sure how the 2 packages are constructing the body with the stream, but as I said, fetch and axios are also producing the exact same error as got.
If you want any of the snippets using fetch or axios I'd be happy to post them as well.
I know this question was asked a while ago, but I too am missing the simple pipe support from the request package
const request = require('request');
request
.get("https://res.cloudinary.com/demo/image/upload/sample.jpg")
.pipe(request.post("http://127.0.0.1:8000/api/upload/stream"))
// Or any readable stream
fs.createReadStream('/Users/file/path/localFile.jpeg')
.pipe(request.post("http://127.0.0.1:8000/api/upload/stream"))
and had to do some experimenting to find similar features from current libraries.
Unfortunately, I haven't worked with "got" but I hope the following 2 examples help someone else that are interested in working with the Native http/https libraries or the popular axios library
HTTP/HTTPS
Supports piping!
const http = require('http');
const https = require('https');
console.log("[i] Test pass-through: http/https");
// Note: http/https must match URL protocol
https.get(
"https://res.cloudinary.com/demo/image/upload/sample.jpg",
(imageStream) => {
console.log(" [i] Received stream");
imageStream.pipe(
http.request("http://localhost:8000/api/upload/stream/", {
method: "POST",
headers: {
"Content-Type": imageStream.headers["content-type"],
},
})
);
}
);
// Or any readable stream
fs.createReadStream('/Users/file/path/localFile.jpeg')
.pipe(
http.request("http://localhost:8000/api/upload/stream/", {
method: "POST",
headers: {
"Content-Type": imageStream.headers["content-type"],
},
})
)
Axios
Note the usage of imageStream.data and that it's being attached to data in the Axios config.
const axios = require('axios');
(async function selfInvokingFunction() {
console.log("[i] Test pass-through: axios");
const imageStream = await axios.get(
"https://res.cloudinary.com/demo/image/upload/sample.jpg",
{
responseType: "stream", // Important to ensure axios provides stream
}
);
console.log(" [i] Received stream");
const upload = await axios({
method: "post",
url: "http://127.0.0.1:8000/api/upload/stream/",
data: imageStream.data,
headers: {
"Content-Type": imageStream.headers["content-type"],
},
});
console.log("Upload response", upload.data);
})();
Looks like this was a headers issue. If I use the headers directly from FormData (i.e., headers: form.getHeaders()) and just add in my additional headers afterwards (Authorization), then this ends up working just fine.
For me just works when I added other parameters on FormData.
before
const form = new FormData();
form.append('file', fileStream);
after
const form = new FormData();
form.append('file', fileStream, 'my-whatever-file-name.mp4');
So that way I can send stream from my backend to another backend in node, waiting a file in multipart/form-data called 'file'

Resources