getting error responses from nft.storage's /store API endpoint using fetch - fetch

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);
})

Related

Cannot convert data to json in angular 13 Content type 'text/plain;charset=UTF-8' not supported] after sending data from angular to .Net core Web Api

I am trying to connect a WebAPI build using .Net core 5
Web API: method
// POST api/<BusController>
//[EnableCors("AllowAllHeaders")]
[HttpPost]
public JsonResult Post([FromBody]BusRequest busRequest)
{
var result = "Response Text";
return new JsonResult(result);
//return result;
}
Angular 13 Code
const busRequest = {
"StartDate" : "02/15/2022",
"EndDate": "02/17/2022",
"BusNo" :null
};
**Approach 1:**
const header = new HttpHeaders();
header.set('Content-Type', 'application/x-www-form-urlencoded;application/json; charset=utf-8');
header.set('Accept','application/json');
const options = {headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;application/json; charset=utf-8', 'Accept': 'application/json'}),
observe: 'response' as 'response',
responseType: 'json' as 'json',
body: busRequest};
this.http.request('post', 'http://localhost:55047/api/bus', options).subscribe();
**Approach 2:**
let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;application/json; charset=utf-8', 'Accept': 'application/json'});
this.http.post('http://localhost:55047/api/bus', JSON.stringify(Request), {headers: headers}).subscribe(data => {
console.log(data);
});
But nothing works.
Response is:
tatus: 415
title: "Unsupported Media Type"
traceId: "00-403257012c151a469a0e24b083d61d62-56ac63710daf8c45-00"
type: "https://tools.ietf.org/html/rfc7231#section-6.5.13"
Did anyone faced the similar problem?

Flutter Dio post an object with array

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

ClientFunction: _axios2 is not defined

I'm running TestCafe for UI automation, using ClientFunctions to trigger API requests (so that I can pass along session cookies).
Currently I have a ClientFunction with fetch which works fine... except we're now testing IE 11 and Fetch is unsupported.
Fetch code:
const fetchRequestClientFunction = ClientFunction((details, endpoint, auth, method) => {
return window
.fetch(endpoint, {
method,
credentials: 'include',
headers: new Headers({
accept: 'application/json',
'Content-Type': 'application/json',
}),
body: JSON.stringify(details),
})
.then(httpResponse => {
if (httpResponse.ok) {
return httpResponse.json();
}
return {
err: true,
errorMessage: `There was an error trying to send the data ${JSON.stringify(
details
)} to the API endpoint ${endpoint}. Status: ${httpResponse.status}; Status text: ${httpResponse.statusText}`,
};
});
});
However when I try to switch it to axios... not so much:
import axios from 'axios';
const axiosRequest = ClientFunction((details, endpoint, auth, method) => {
return axios({
method,
auth,
url: endpoint,
data: details,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
timeout: 3000,
})
.then(httpResponse => {
if (httpResponse.status < 300) return httpResponse;
return {
err: true,
errorMessage: `There was an error trying to send the data ${JSON.stringify(
details
)} to the API endpoint ${endpoint}. Status: ${httpResponse.status}; Status text: ${httpResponse.statusText}`,
};
});
});
Tried using window.axios, and also passing axios as a dependency. I've also tried making the axios request without the ClientFunction... and despite getting response of 200, the website wasn't updated as expected.
Each time I either get _axios2 is not defined or window.axios is not a function. I would greatly appreciate some guidance here.
TestCafe ClientFunctions allow only serializable objects as dependencies. You need to have axios on the client side to send such a request.

Rails API not receiving fetch POST data from body

I have a route in Rails API '/api/pay'. My client side post request successfully hits the controller action, however nothing I send in the body: JSON.stringify('...') gets through to the back-end. Other post requests I have made work just fine with the same format.
export const payForItem = (payData) => {
return dispatch => {
dispatch(payForItemStart());
// ?userID=${data.userID}&adID=${data.adID}&price=${data.price}
const data = {userID: payData.userID, adID: payData.adID, price: payData.price}
fetch(`/api/pay`, {
method: 'POST',
header: {
'content-type': 'application/json'
},
body: JSON.stringify(data)
})
Here is what payData looks like.
Rails Api back-end params
Probably you've got typo in headers section. Should be plural headerS with s:
headers: {
"Content-Type": "application/json"
}

Google Closure Compiler warns of "expressions are not callable"

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) {
});

Resources