For the life of me, I can't work this out... (js noob)
My JSON body looks like this:
{
"title": "Example 1",
"job": "Designer A"
}
But the API wants it inside an array like:
[ {
"title": "Example 1",
"job": "Designer A"
} ]
How can I achieve this?.
function handleForm(ev) {
ev.preventDefault();
let jobForm = ev.target;
let fd = new FormData(jobForm);
//look at all the contents
for (let key of fd.keys()) {
console.log(key, fd.get(key));
}
let json = convertFD2JSON(fd);
//send the request with the formdata
let url = 'HIDDEN_URL';
let h = new Headers();
h.append('Content-Type', 'application/json');
let req = new Request(url, {
mode: 'cors', // no-cors, *cors, same-origin
headers: h,
body: json,
method: 'POST',
});
fetch(req)
.then((res) => res.json())
.then((data) => {
console.log('Response from server');
console.log(data);
})
.catch(console.warn);
}
function convertFD2JSON(formData) {
let obj = {
};
for (let key of formData.keys()) {
obj[key] = formData.get(key);
}
return JSON.stringify(obj);
}
Thanks!!
This one's actually pretty straightforward! We can simply alter the following code:
let req = new Request(url, {
mode: 'cors', // no-cors, *cors, same-origin
headers: h,
body: json,
method: 'POST',
});
To be like this:
let req = new Request(url, {
mode: 'cors', // no-cors, *cors, same-origin
headers: h,
body: [json],
method: 'POST',
});
The difference is in the code above, I encase the JSON variable in [] which defines it as the only element in a new array. This should work exactly how you need it to!
Related
I have migrated a piece of code to be able to export data as excel file in angular.
I assume the fact that the json is well formed and send from the server to the angular side. I can see it in the network frame in th browser.
For small json, it's ok but when the size of the json starts to be large, the answer still failed.
This following code corresponding to the service call
exportSynthesis(recordId: number, moduleId: number) {
const body = null;
return this.http.post(this.apiUrl + `/data`
+ `${recordId}/module/${moduleId}`, body,
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response', responseType: 'json' }).pipe(
map((resp: any) => {
return resp.body;
}));
}
and here, its the method which manages the return.
exportSynthesis() {
this.service.exportSynthesis(this.recordId, this.moduleId)
.subscribe(
(exportResult) => { this.exportResult = exportResult; },
err => {
console.log('err:', err);
this.errorHandlerService.handleError('failed', err);
},
() => {
console.log('json:', this.exportResult);
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.exportResult);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '(GEO) ' + this.record.label + ' - name.xlsx';
a.click();
window.URL.revokeObjectURL(url);
a.remove();
});
}
Currently, i do not manage to understand why it still finish in error and I get only "ok" in the console log.
Any idea?
regards
Angular's HttpClientModule default response is a json.
Your problem is that you try to access the body property of the HTTP response, but Angular interprets that as you trying to access the body property in the body of the response.
Remove observe and responseType from your post request and treat the response as a json. It should work.
find:
just need to use text as json
return this.http.post(this.apiUrl + `/geo/v1/synthesis/xls/record/`
+ `${recordId}/module/${moduleId}`, body,
{
headers: headers,
observe: 'response',
responseType: 'text' as 'json'}).
map((resp: any) => {
return resp.body;
});
}
Day one with Cypress.
Trying to make a JSON call and examine result but all attempts giving me undefined.
describe('Test Number 000001 !!!', function() {
it('starts off OK', function() {
expect(true).to.equal(true)
})
it('can call the example api', function() {
cy.request('https://jsonplaceholder.typicode.com/todos/1')
})
it('can call the example api and store the result', function() {
result = cy.request('http://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json()) // I tried with and without then
expect(result).to.equal(1) // will fail but once i get real response I will adjust
})
})
Update: the below passes... but doesn't actually check anything (any values used will pass)
cy.request('http://jsonplaceholder.typicode.com/todos/1').
then((response) => {
response = JSON.stringify(response)
var jsonData = JSON.parse(response)
for (var i = 0; i < jsonData.length; i++) {
expect(jsonData[i]['xuserId']).to.equal(1)
}
})
I have used the same test API earlier and have got the results like below; Please have a look. I have used response.body. to get json values
it('Sample Api testing', function () {
cy.request({
method: 'get',
url: 'https://jsonplaceholder.typicode.com/todos/1',
headers: {
'accept': 'application/json'
}
}).then((response) => {
expect(response.status).to.eq(200);
expect(response.body.userId).to.eq(1);
expect(response.body.id).to.eq(1);
expect(response.body.title).to.eq('delectus aut autem');
})
})
You need to convert response object to a json string using stringify function inside the promise.
.then((response) => {
response = JSON.stringify(response)
var jsonData = JSON.parse(response)
for (var i = 0; i < jsonData.length; i++) {
expect(jsonData[i]['userId']).eq(1)
}
edit
expect(jsonData[i]['userId']).to.equal(1)
I'm trying to make an http request to an API that takes an image and detects if there's any nudity in the image.
API Source: https://rapidapi.com/macgyverapi/api/nudity-detection/endpoints
Expected Response:
"{ "true": "0.977926", "false": "0.0220745" }"
My attempt below produces the error:
I/flutter ( 9838): {error: The algorithm generated an error on that request}
Below is my code and a working HTTP version under that
My Attempt:
import 'package:http/http.dart' as http;
import 'dart:convert';
void main(List<String> arguments) async {
var url = 'https://macgyverapi-nudity-detection-v1.p.rapidapi.com/';
// Await the http get response, then decode the json-formatted response.
var body = json.encode({'key': 'free', 'id': '8E5q5T2p', 'data': {'image': 'https://askmacgyver.com/images/nude.jpg'}});
Map<String,String> headers = {'x-rapidapi-host': 'macgyverapi-nudity-detection-v1.p.rapidapi.com','x-rapidapi-key': '5fbb8f70e6msh04e1ddd09f7fbb9p109a04jsn386ca971275a', 'content-type': 'application/json', 'accept': 'application/json'};
final response = await http.post(url, body: body, headers: headers);
final responseJson = json.decode(response.body);
print(responseJson);
}
Working HTTP Version:
var http = require("https");
var options = {
"method": "POST",
"hostname": "macgyverapi-nudity-detection-v1.p.rapidapi.com",
"port": null,
"path": "/",
"headers": {
"x-rapidapi-host": "macgyverapi-nudity-detection-v1.p.rapidapi.com",
"x-rapidapi-key": "5fbb8f70e6msh04e1ddd09f7fbb9p109a04jsn386ca971275a",
"content-type": "application/json",
"accept": "application/json"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(JSON.stringify({
key: 'free',
id: '8E5q5T2p',
data: {image: 'https://askmacgyver.com/images/nude.jpg'}
}));
req.end();
I try to post an image with http.post from Angular6.
See below my rest service and component.
Service
setOptions(data: boolean = false, headersToSet?: any): any {
let token: string;
const headers = [];
token = JSON.parse(localStorage.getItem('SOSF_MANAGER_TOKEN'));
// AUTHORIZATION
headers['Authorization'] = 'Bearer ' + token;
headers['Content-Type'] = data ? 'multipart/form-data' : 'application/json';
// OTHER HEADERS
if (headersToSet !== undefined) {
for (const headerName of Object.keys(headersToSet)) {
headers[headerName] = headersToSet[headerName];
}
}
return { headers };
}
// POST
postDb(url: string, body: any): Observable<any> {
let options: any;
options = this.setOptions(body instanceof FormData);
url = this.url + url;
if (!(body instanceof FormData)) {
body = JSON.stringify(body);
} else {
// TO DO
}
console.log(body);
if (environment.console_log_construct) {
console.log(`POST : ${url}`);
}
return this.http.post(url, body, options).pipe(
map(response => {
return response;
}, error => {
console.error(`POST ERROR: ${url}`, error);
}));
}
Component
// Open Our formData Object
const formData = new FormData();
// Append our file to the formData object
formData.append('file', files[0]);
// POST
this.restService.postDb('files/images', formData)
.subscribe(response => {});
If I let JSON.stringify(body) when body is formData, formdata is set to {}. But if I let body like this, it throw a error 'Uncaught SyntaxError: Unexpected token o in JSON at position 1'. How can I achieve it ?
I'm trying to do a POST on ionic submitting a form with an array of data but I don't know how I can do this (but if I do this in POSTMAN, it actually works).
I tried with this form but didn't work:
submitRegistration(value):void{
var headers = new Headers();
let options = new RequestOptions({headers: headers});
headers.append("Content-Type", 'application/json');
let link = 'http://apidata.com/';
let myData = {
fos_user_registration_form: [{
_token: this.data.token,
username: value.usuario,
email: value.correo,
plainPassword: [{
first: value.password,
second: value.confirmPassword
}],
userLocalization: value.municipio}
]};
console.log(myData);
this.http.post(link, myData, options)
.subscribe(data => {
this.data.response = data["_body"];
}, error => {
alert("Oooops!");
});
}
Can anyone help me?
You have to stringify the data before you post,try this
this.http.post(link, JSON.stringify(myData), options)
.subscribe(data => {
this.data.response = data["_body"];
}, error => {
alert("Oooops!");
});
It should do the trick
Finally i find the solution (for me). Here the code
submitRegistration(value):void{
var headers = new Headers();
let options = new RequestOptions({headers: headers});
headers.append("Content-Type", 'application/x-www-form-urlencoded');
let link = 'http://APIREST.com/';
let myData = 'fos_user_registration_form[_token]='+encodeURI(this.data.token);
myData += '&fos_user_registration_form[username]='+encodeURI(value.usuario);
myData += '&fos_user_registration_form[email]='+encodeURI(value.correo);
myData += '&fos_user_registration_form[plainPassword][first]='+encodeURI(value.password);
myData += '&fos_user_registration_form[plainPassword][second]='+encodeURI(value.confirmPassword);
myData += '&fos_user_registration_form[userLocalization]='+encodeURI(value.municipio);
console.log(myData);
this.http.post(link, myData, options)
.subscribe(data => {
this.data.response = data["_body"];
console.log(data);
}, error => {
console.log("Oooops!");
});
}