const req = require('request')
let base = 'https://openapi-v2.kucoin.com';
let endpoint = '/api/v1/orders';
let url = base + endpoint;
req.post(url,params,config,(err,body,res)=>{
if (err) { return console.log(err); }
console.log(res)
})
i try to request post but error lnvalid URI " / "
I don't know how to fix this.
Error Photo
According to the request's document, The post method does not receive 4 arguments. Set your config and data into the first argument:
request.post({
url:'http://service.com/upload',
form: {key:'value'}
}, function(err,httpResponse,body){ /* ... */ })
Also the order of err,body,res is incorrect.
Use something like this one:
req.post({
url: url,
params: data,
X: config.X,
Y: config.Y
}, (err,httpResponse,body)=>{
if (err) { return console.log(err); }
console.log(res)
})
Related
I have an issue with binance API signature for their REST API.
When trying to hit the route 'http://binance.com/api/v3/account', I get the following error:
{"code":-1022,"msg":"Signature for this request is not valid."}
I use nodejs and express.
I've seen there is a few questions on this subject but none seems to solve my problem so:
I define keys and urls there
const binanceConfig = {
API_URL: 'http://binance.com',
API_ENDPOINT: '/api/v3/account',
API_KEY: 'API_KEY_EXAMPLE',
API_SECRET: 'API_SECRET_EXAMPLE'
}
I create the signature
function generateSignature() {
const dataQueryString = "recvWindow=60000×tamp=" + Date.now();
return crypto
.createHmac('sha256', binanceConfig['API_SECRET'])
.update(dataQueryString)
.digest('hex');
}
I define query parameters here
const queryParameters = {
timestamp: Date.now(),
signature: generateSignature(),
recvWindow: '60000',
}
Set the header
var header = {
'Accept': 'Application/json',
'X-MBX-APIKEY': binanceConfig['API_KEY']
};
Create the route to call the API
router.get('/userInfo', (req, res) => {
var stringTest = `timestamp=${queryParameters['timestamp']}`
requestUrl = binanceConfig['API_URL'] + binanceConfig['API_ENDPOINT'] + "?" + stringTest + "&" + "signature=" + queryParameters['signature'] + "&recvWindow=" + queryParameters['recvWindow'];
const options = {
url: requestUrl,
headers: header,
method: 'GET'
}
request(options, (error, response) => {
if (error) { console.log('ERROR'); }
console.log(`Response: ${response.statusCode}`);
console.log(response.body);
});
});
If anyone has any idea why I get this error I'd be gratefull ! Thanks !
You need to have the timestamp and signature (respectively) as the last parameters.
Source
I have the following lambda function that works when called from the front-end React app:
// Update a contact
module.exports.updateContact = async (event, _context) => {
const id = event.pathParameters.id;
const body = JSON.parse(event.body);
const paramName = body.paramName;
const paramValue = body.paramValue;
const params = {
Key: {
id: id
},
TableName: contactsTable,
ConditionExpression: 'attribute_exists(id)',
UpdateExpression: 'set ' + paramName + ' = :v',
ExpressionAttributeValues: {
':v': paramValue,
},
ReturnValues: 'ALL_NEW'
};
try {
const res = await db.update(params).promise();
}
catch (err){
console.log(err);
return err;
}
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
status: 'updated!',
[paramName]: paramValue,
}),
};
return response;
};
But it fails with status code 502 & 'InternalServerErrorException' message when called from Postman.
I tried to solve it with one of the suggestions found on stackoverflow with method override:
It doesn't work and I'm now getting status code 403 and 'MissingAuthenticationTokenException'.
I'm not sure what I'm doing wrong, seeking some guidance. Thank you.
It seems the API endpoint has an Authorizer configured on the API Gateway and the front end is sending the correct credentials, while the Postman configuration is not.
I would suggest to use the browser dev tools selecting the PUT request and copy it as cUrl:
then you can paste the copied cUrl command into the Postman request. It will prefill all the parameters: method, body and the headers.
hope this help
Trying to figure out the right way to send a RESTful request to an API using the Node.js Needle library. I think everything is right except the code concerning the image URL. No matter how I try to change what it looks like or where I put it, I keep getting an error that says it's an invalid image, but it's not, the URL is fine. So, my guess is my code is wrong and so whatever it thinks is the URL for the image, is probably not the URL (but maybe some other code or code in a location that should be where the body/image URL is).
const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.jpg'
// Request parameters.
const params = {
returnFaceId: true,
returnFaceLandmarks: false,
returnFaceAttributes: 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
}
var options = {
body: '{"url": ' + '"' + imageUrl + '"}',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscriptionKey
}
}
needle.post(endpoint, params, options, function (err, res, body) {
console.log(`Status: ${res.statusCode}`)
console.log('Body: ', body)
console.log('ERROR: ' + err)
//console.log(res)
})
I have also tried to write the body like a plain ol' object: body = { 'url': imageURL}, but still getting the same error.
Error:
Status: 400
Body: { error: { code: 'InvalidURL', message: 'Invalid image URL.' } }
Here is the API I am trying to call, which has been confirmed to work with other samples:
https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236
For this request you have a combination of parameters:
Some of them as query strings (your 'params')
Some of them as a body payload (your options.body)
Therefore, it seems that you cannot use needle.post directly because it can do query string params OR body param but not both at the same time.
So there are several options:
Set your query string params in the URL field
Change your lib
For the 1st option, here is an example:
const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.jpg'
// Request parameters.
const params = {
returnFaceId: true,
returnFaceLandmarks: false,
returnFaceAttributes: 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
}
// Adding params to query string
serialize = function(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
endpoint = endpoint + "?" + serialize(params)
// Setting body and options
var body = '{ "url": ' + '"' + imageUrl + '"}'
var options = {
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscriptionKey
}
}
needle.post(endpoint, body, options, function (err, res, body) {
console.log(`Status: ${res.statusCode}`)
console.log('Body: ', body)
console.log('ERROR: ' + err)
//console.log(res)
})
My PUT request always fails the first time after a server restart, but works after the first attempt has failed. My GET/DELETE/POST requests works fine all the time.
I tried having the itemid as a const instead of having it as a global variable to make sure it was not a async problem regarding that variable
public async PutSomething(metadataObject: any, id: any) {
const params = {"id": id};
const itemidquery = "SELECT itemid FROM archive WHERE id = " + "${id};";
let itemid: any;
try {
itemid = await connection.db.one(itemidquery, params);
}
catch (e) {
console.log(e);
}
console.log("The itemid for the item to be updated" + itemid.itemid);
const urlFinal = BASEURL + "items/" + itemid.itemid + "/metadata";
console.log(urlFinal);
const headersOpt = {
"rest-dspace-token": process.env.TOKEN,
"content-type": "application/json"
};
const options = {
rejectUnauthorized: false,
method: "PUT",
uri: urlFinal,
headers: headersOpt,
body: metadataObject,
json: true,
encoding: "utf8",
};
rp(options)
.then(async function (res: Response, req: Request) {
console.log("Successful PUT" + res as any);
})
.catch(function (err: Error) {
console.log("Error while updating julkaisu: " + id + " with error: " + err);
});
}
This should work fine in my opinion, since all my other API routes works fine, GET/DELETE/POST etc. This just fails the first time after a server restart, no matter what. After that it keeps working fine.
Anyone have any idea what might cause this?
I'm trying to implement https://developers.podio.com/doc/items/add-new-item-22362 Podio API addItem call in a nodejs module. Here is the code:
var _makeRequest = function(type, url, params, cb) {
var headers = {};
if(_isAuthenticated) {
headers.Authorization = 'OAuth2 ' + _access_token ;
}
console.log(url,params);
_request({method: type, url: url, json: true, form: params, headers: headers},function (error, response, body) {
if(!error && response.statusCode == 200) {
cb.call(this,body);
} else {
console.log('Error occured while launching a request to Podio: ' + error + '; body: ' + JSON.stringify (body));
}
});
}
exports.addItem = function(app_id, field_values, cb) {
_makeRequest('POST', _baseUrl + "/item/app/" + app_id + '/',{fields: {'title': 'fgdsfgdsf'}},function(response) {
cb.call(this,response);
});
It returns the following error:
{"error_propagate":false,"error_parameters":{},"error_detail":null,"error_description":"No matching operation could be found. No body was given.","error":"not_found"}
Only "title" attribute is required in the app - I checked that in Podio GUI. I also tried to remove trailing slash from the url where I post to, then a similar error occurs, but with the URL not found message in the error description.
I'm going to setup a proxy to catch a raw request, but maybe someone just sees the error in the code?
Any help is appreciated.
Nevermind on this, I found a solution. The thing is that addItem call was my first "real"-API method implementation with JSON parameters in the body. The former calls were authentication and getApp which is GET and doesn't have any parameters.
The problem is that Podio supports POST key-value pairs for authentication, but doesn't support this for all the calls, and I was trying to utilize single _makeRequest() method for all the calls, both auth and real-API ones.
Looks like I need to implement one for auth and one for all API calls.
Anyway, if someone needs a working proof of concept for addItem call on node, here it is (assuming you've got an auth token beforehand)
_request({method: 'POST', url: "https://api.podio.com/item/app/" + app_id + '/', headers: headers, body: JSON.stringify({fields: {'title': 'gdfgdsfgds'}})},function(error, response, body) {
console.log(body);
});
You should set content-type to application/json
send the body as stringfied json.
const getHeaders = async () => {
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8',
};
const token = "YOUR APP TOKEN HERE";
headers.Authorization = `Bearer ${token}`;
return headers;
}
const createItem = async (data) => {
const uri = `https://api.podio.com/item/app/${APP_ID}/`;
const payload = {
fields: {
[data.FIELD_ID]: [data.FIELD_VALUE],
},
};
const response = await fetch(uri, {
method: 'POST',
headers: await getHeaders(),
body: JSON.stringify(payload),
});
const newItem = await response.json();
return newItem;
}