I am trying to post a request to api with an object as"
var params = {
"item": "itemx",
"options": [1,2,3],
};
print(params);
try {
Response response = await _dio.post(getAddToCartURL,
queryParameters: params,
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/json",
}));
} catch (error, stackTrace) {
print("Exception occurred: $error stackTrace: $stackTrace");
return false;
}
Dio sends the object as :
POST /api/add-to-cart/?item=itemx&options%5B%5D=1&options%5B%5D=2&options%5B%5D=3
in which the api recognize it as a bad request.
what is wrong that i am doing here? I have even tried the list as [ "1","2","3"], it is the same.
It all depends on how the API expects it. I would suggest trying to encode it as JSON.
var params = {
"item": "itemx",
"options": jsonEncode([1,2,3]),
};
But sending complex data in query parameters isn't always that easy. Since you are using POST anyway, maybe send a JSON object as body instead of using query parameters.
var params = {
"item": "itemx",
"options": [1,2,3],
};
...
Response response = await _dio.post(getAddToCartURL,
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/json",
}),
data: jsonEncode(params),
);
another example for any one might be helpful , posting fomr data
var formData = FormData.fromMap({
'data': json.encode(
{'salt': salt, 'placeholder': 'palceholder',
'method_name': 'app_details'})
});
var response = await dio.post(
BaseUrl,
data: formData,
);
the final result of your request is this
Related
let formData = new FormData();
formData.append("name",name);
formData.append("description",description);
formData.append("image", image);
fetch("https://api.nft.storage/store",{
method: "POST",
body: formData,
headers: {
'Authorization': 'Bearer '+process.env.TEST_API_KEY,
}
}).then(response => response.json())
.then((json)=>{
console.log(json)
})
This is what I've been trying to do but keep getting error as a response. Errors are usually invalid-file or something to do with content-type.
https://nft.storage/api-docs/ - This is the api documentation. If theres any example for the same, it'll be really helpful. Thanks!
Long time since question... just for any one wondering:
The api endpoint receives 1 parameter called meta which is a json_encoded representation of the fields, any falsy value like image: undefined, will be replaced with an extra field you must include, with the binary representation of the field... here is an example:
let params = {
name: 'name of the nft',
image: undefined,
description: 'description of the nft'
}
let formData = new FormData();
formData.append("meta",JSON.stringify(params));
formData.append("image",new File([ someBinaryImageData ], 'nft.png', { type: 'image/png' });
fetch("https://api.nft.storage/store",{
method: "POST",
body: formData,
headers: {
'Authorization': 'Bearer '+process.env.TEST_API_KEY,
}
})
.then(response => response.json())
.then((json)=>{
console.log(json);
})
I'm following thist tutorial : https://cloud.google.com/tasks/docs/tutorial-gcf
To create a Task that would call a cloud function.
I've done quite some tries and still get this error:
If I change the body encoding to something else, I get another error about serialisation method.
It's likely not a permission issues, as I got some before and got rid of it.
The object which is pass to the createTask() is the following :
task: {
httpRequest: {
url: "https://europe-west1-project_id.cloudfunctions.net/FunctionName"
httpMethod: "POST"
oidcToken: {
serviceAccountEmail: "cf-targetFunctionSA#project_id.gserviceaccount.com"
}
body: ""
headers: {
Content-Type: "application/json"
}
}
(or with body: base64 encoded json string.)
The code I use is the following :
'use strict';
const common = require('./common');
const {v2beta3} = require('#google-cloud/tasks');
const cloudTasksClient = new v2beta3.CloudTasksClient();
let projectName = common.getProjectName();
let location = "europe-west3";
let queue = "compute-stats-on-mysql";
const parent = cloudTasksClient.queuePath(projectName, location, queue);
async function createTask(url, serviceAccount, data)
{
const dataBuffer = Buffer.from(JSON.stringify(data)).toString('base64');
const task = {
httpRequest: {
httpMethod: 'POST',
url:url,
oidcToken: {
serviceAccountEmail: serviceAccount,
},
headers: {
'Content-Type': 'application/json',
},
body:dataBuffer,
},
};
try
{
// Send create task request.
common.logDebug(`Before creating task`, {parent:parent,task:task, data:data});
const [response] = await cloudTasksClient.createTask({parent, task});
common.logDebug(`Created task ${response.name}`, {parent:parent,task:task, response:response, data:data});
return response;
}
catch (error)
{
// Construct error for Stackdriver Error Reporting
console.error("error while creating tasks",error);
}
}
module.exports = {
createTask : createTask,
cloudTasksClient:cloudTasksClient
};
The lack of details in the error makes me hit a wall blind...
Any suggestions ?
My service account was missing a part...
it was
"cf-"+functionName+"#"+projectName+".gserviceaccount.com";
instead of
"cf-"+functionName+"#"+projectName+".iam.gserviceaccount.com";
I left out the ".iam" during my numerous test to make it work.
For sure there's room for improvement in the error messages.
I had same problem. In your case I think there is not property scheduleTime into task param.
To me, the scheduleTime.seconds was with a wrong value.
In the following code, I get the warning:
expressions are not callable
I am using the Google Closure Compiler. The warning occurs when the request object is called as a function. How can I get rid of this warning?
var request = require('request'); // See https://github.com/request/request
request({
url: "https://www.googleapis.com/oauth2/v4/token",
method: "POST",
json: false,
body: tokenPostData,
headers: {
"content-type": "application/x-www-form-urlencoded"
},
}, function (error, response, body) {
});
Figured out the solution. Just add "call" after the request object and make sure the first parameter value is "this".
var request = require('request'); // See https://github.com/request/request
request.call(this, {
url: "https://www.googleapis.com/oauth2/v4/token",
method: "POST",
json: false,
body: tokenPostData,
headers: {
"content-type": "application/x-www-form-urlencoded"
},
}, function (error, response, body) {
});
i am new to angular2 native script programming.. i need to post data to a particular url from my app. when i try to post data then get a message on console Response with status: 200 for URL: null. whats the meaning of this message.? and what should i do for successfull post request..?
//my code
let headers = new Headers({ "Content-Type": "application/json" });
let options = new RequestOptions({ headers: headers });
let body =
{
"firstName": "boby",
"lastName": "samuels",
"Location": "UK"
};
this.http.post("http://example.com", JSON.stringify(body), options)
.subscribe(result =>
{
console.log("response : "+result);
}, error =>
{
console.dir(error);
});
please help me out.
I am trying to get the sentiment of a piece of text using th AlchemyAPI in my meteor application. I am using HTTP.call with 'POST' as recommended by the API to make a server to server call, but I am getting an 'invalid-api-key' response.
var alchemyURL = Meteor.settings.alchemyUrl;
var postData = {
'apikey': Meteor.settings.alchemyUrl,
'text': txt,
'outputMode': 'json'
};
var options = {
data: postData
};
var sentimentData = HTTP.call('POST', alchemyURL, options);
console.log(sentimentData);
I have discovered the answer, to this hence posting it in below.
So turns out, Meteor's HTTP package needs to be given the headers for implementing form url-encoding on the data. Also the data object needs to be passed in 'params' and not in 'data' The correct snippet to be used is given below.
var alchemyURL = Meteor.settings.alchemyUrl;
var postData = {
'apikey': Meteor.settings.alchemyUrl,
'text': txt,
'outputMode': 'json'
};
var options = {
params: postData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
var sentimentData = HTTP.call('POST', alchemyURL, options);
console.log(sentimentData);