Why when I do a console.log(), just after the last form.append("","") work well I see what I push in them, and than when I watch on the backend is blanked ?
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client this error occured when I adding "Content-Type": "multipart/form-data" on the headers , do you know what happended ???
const uri = pictureUri.uri;
const uriParts = uri.split(".");
const fileType = uriParts[1];
const form = new FormData();
form.append("categorie","someCategorieInthere");
form.append("picture", {
uri,
name: `picture.${fileType}`,
type: `image/${fileType}`,
});
const handlSubmit = async () => {
try {
await axios.put("blablbla_url",
form,
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "multipart/form-data",
},
}
);
} catch (error) {
console.log({ message: error });
}
};
Related
Below is my code I keep getting error that it is unprocessable i looked it up and it said
to assign headers to content-type : "application/json" and i am still getting the errors.
export async function action({ request, params }) {
const data = await request.formData();
const eventData = {
title: data.get("title"),
Image: data.get("image"),
date: data.get("date"),
description: data.get("description"),
};
console.log(JSON.stringify(eventData));
const stringData = JSON.stringify(eventData);
const response = await fetch("http://localhost:8080/events", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: stringData,
});
console.log(response);
if (!response.ok) {
throw json({ message: "Could not save event" }, { status: 500 });
}
return redirect("/events");
}
it says server is expecting json and i have converted the data to json and still getting the error
I create my API using v3 of Drive Api and usign uploadType=resumable, the server return me status code 200 and the metadata for the file, but when I see in drive, the file isn't there
// Client
googleClientRequest() {
const keysEnvVar = process.env["CREDS"];
if (!keysEnvVar) {
throw new Error("The $CREDS environment variable was not found!");
}
const keys = JSON.parse(keysEnvVar);
return new GoogleAuth({
scopes: [
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
],
credentials: keys,
});
// Initial request
const initialFile = await client.request({
url:
"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
method: "POST",
headers: {
"Content-Type": "application/json; charset=UTF-8",
Accept: "application/json",
},
data: {
name: `${job.data.callId}.mp3`,
},
});
// File upload
async doUpload(fileLink: string, driveLink: string) {
const client = this.googleClientRequest();
const { data, headers } = await axios({ // The file comes from zoom api is a recorder
method: "GET",
url: fileLink,
responseType: "arraybuffer",
});
const response = await client.request({
url: driveLink,
headers: {
"Content-Type": "application/json; charset=UTF-8",
"X-Upload-Content-Type": "audio/mp3",
"X-Upload-Content-Length": headers["zoom-file-size"],
},
method: "POST",
data: Buffer.from(data),
});
console.log(response.status, response.data, response.statusText);
return response;
}
// The response
200 OK
{
kind: 'drive#file',
id: '######',
name: '1e9af0f9-9d3e-4287-a9fa-7cb3d229c1ad.mp3',
mimeType: 'audio/mp3'
}
I try everything, I try with this example Angular 2+ HTTP POST and GDrive API. Resumable file upload with name
I would like to upload an image to Google Photos inside my Angular-App using the Google Photos API. Everything is working out until I want to create the "MediaItem" using the uploadToken I received before. My code is looking like this:
Getting the uploadToken...
getUploadToken(imageBase64: string) {
let binaryImage = Buffer.from(imageBase64, 'base64');
const uploadHeaders = new HttpHeaders({
'Authorization': `Bearer ${this.accessToken}`,
'Content-type': 'application/octet-stream',
'X-Goog-Uploadd-Content-Type': 'image/jpeg',
'X-Goog-Upload-Protocol' : 'raw',
'observe': 'response'
});
const httpUploadHeaders: Object = {
headers: uploadHeaders,
responseType: 'text'
}
this.http.post('https://photoslibrary.googleapis.com/v1/uploads', binaryImage, httpUploadHeaders)
.subscribe(data => {
this.uploadToken = data;
this.createMediaItem(this.uploadToken);
});
};
Creating an album (this is optional):
createAlbum(): void {
const createAlbumHeaders = new HttpHeaders({
'Content-type': 'application/json',
'Authorization': `Bearer ${this.accessToken}`
});
const httpCreateAlbumHeaders: Object = {
headers: createAlbumHeaders,
responseType: 'json'
};
const body = {
"album": {
"title": "Test"
}
}
this.http.post('https://photoslibrary.googleapis.com/v1/albums', JSON.stringify(body), httpCreateAlbumHeaders)
.subscribe(data => {
return data['id'];
});
}
Finally, creating the mediaItem (or at least trying to):
createMediaItem(uploadToken: string): void {
const createMediaItemHeaders = new HttpHeaders({
'Content-type': 'application/json',
'Authorization': `Bearer ${this.accessToken}`
});
const httpCreateMediaItemHeaders: Object = {
headers: createMediaItemHeaders
}
const albumId = this.createAlbum();
const body = {
"albumId": albumId,
"newMediaItems": [
{
"description": "Testupload",
"simpleMediaItem": {
"fileName": 'Test',
"uploadToken": uploadToken
}
}
]
}
this.http.post('https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate', JSON.stringify(body), httpCreateMediaItemHeaders)
.subscribe(data => {
console.log(data);
});
}
The error I'm getting from the httpResponse is:
Code: 3
message: "Failed: There was an error while trying to create this media item."
I would really appreciate some help with that. I'm slowly becoming desperate.
Thank you!
I am testing an api which requires to send an image in the request body but I am getting error,
Here's my code:
it("should register a new litigant/customer", () => {
cy.fixture('testImg1.png', "base64").then(base64 => {
const blob = Cypress.Blob.base64StringToBlob(base64, 'image/png')
const bodyObj = {
email: "customer#customer.com",
password: "123456789",
profilePicture: blob
}
let formData = new FormData()
for (let key in bodyObj){
formData.append(key, bodyObj[key])
}
cy.request({
method: "POST",
url: endpoints.signup.litigant,
headers: { "content-type": "application/x-www-form-urlencoded" },
body: formData,
}).then(res => {
expect(...)
})
})
})
But I am getting this error:
Does anyone know how to fix this??
I am working on a project where I need to create a short URL for a link using bitly.
I got success by using the request package of Nodejs.
This is what I have done so far.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
var options = {
url: api_url,
method: "POST",
headers: headers,
body: dataString,
};
request(options, (error, body) => {
if (error) {
return res.status(404).send(error);
}
return res.render("index", { error: "", data: JSON.parse(body.body) });
});
my question is how can we use Axios instead of the request package because the request package is deprecated.
I tried but did not get success.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
const response = await axios.post(
api_url,
{ long_url: req.body.url },
{
headers: headers,
}
);
return res.render("index", { error: "", data: response });
I am getting errors like the body is not defined.
Please help me. Thank you!
const response = await axios.post(api_url, dataString, {
headers: headers,
});
console.log(response.data);
return res.render("index", { error: "", data: response.data });