hope you all doing fine,
currently i am working on a small html static project and i have image uploading there so i used imgur api, i tested it out on postman it seems pretty okay, but when i try to code it like that
var myHeaders = new Headers();
myHeaders.append("Authorization", "Client-ID ******");
myHeaders.append("Access-Control-Allow-Origin", "*");
var formdata = new FormData();
formdata.append("image", image);
var requestOptions = {
method: "POST",
headers: myHeaders,
body: formdata,
redirect: "follow",
};
fetch("https://api.imgur.com/3/upload", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
i only got this error
cross origin resource sharing error header disallowed preflight response
am i doing something wrong here
Related
I want to to call post API with image attached in body. I have browsed and tried available solutions but didnt work(getting 400 as error). Solutions tried -
File which is browsed I have created a filereader object and called readAsDataURL(). It gave undefined error(bad request error)
let reader = new FileReader()
reader.readAsDataURL(event.target.files[0]);
fetch('some endpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: reader, //(reader.result also i tried)
})
.then((response) => response.json())
.then((json) => console.log(json))```
Second approach was creating a dataform, even this gave bad request as error
<form class="form" id="myForm">
<input type="file" id="fileUpload" accept="image/*" onchange="previewImage(event);"/>
</form>```
```const inpFile = document.getElementById('fileUpload');
const formData = new FormData();
formData.append('inpFile', event.target.files[0]);
fetch(some endpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: formData,
})
.then((response) => response.json())
.then((json) => console.log(json))```
screenshot of error
The second approach is correct except your headers. try changing them to 'Content-Type': 'multipart/form-data'.
you are not posting JSON data but FormData.
I am trying to upload SVG data using fetch API and multipart/form-data content-type but its throwing 400 error code.
var myHeaders = new Headers();
myHeaders.append("Content-type", "multipart/form-data");
var formData = new FormData();
formData.append("front_svg",stage.canvas.toSVG());
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formData,
redirect: 'follow'
};
fetch("api-url", requestOptions).then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Overview
I'm attempting to upload asset to github using Javascript fetch request. It works in Postman
Postman
Error
but in javascript I get this error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://uploads.github.com/repos/{owner}/{repo}/releases/{id}/assets?name=windows.zip. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400.
I've been working on this for a few days now...
Thanks in advance
Javascript CODE
async function OpenFile() {
let input = document.createElement("input")
input.type = "file";
input.accept = "application/zip";
input.addEventListener("change", async e => {
let file = e.currentTarget.files[0];
let reader = new FileReader();
reader.addEventListener('load', () => {
let content = reader.result;
let myHeaders = new Headers();
myHeaders.append("Authorization", `token *****`);
myHeaders.append("Content-Type", "application/zip");
myHeaders.append("Accept", "application/vnd.github+json");
let requestOptions = {
method: 'POST',
headers: myHeaders,
body: content,
mode: 'cors'
};
fetch(`https://uploads.github.com/repos/{OWNER}/{REPO}/releases/{ID}/assets?name=file.zip`, requestOptions)
.then(response => response.json())
.then(json => {
console.log(JSON.stringify(json))
}).catch(error => { console.log(error) })
}, false)
reader.readAsArrayBuffer(file)
})
input.click();
}
P.S.
I removed sensitive information from the urls
Edit:
Github API states that you should be able to use this
// Octokit.js
// https://github.com/octokit/core.js#readme
const octokit = new Octokit({
auth: 'personal-access-token123'
})
await octokit.request('POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}', {
owner: 'OWNER',
repo: 'REPO',
release_id: 'RELEASE_ID'
})
OR
var myHeaders = new Headers();
myHeaders.append("Authorization", "token ******");
myHeaders.append("Content-Type", "application/zip");
var file = "<file contents here>";
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: file,
redirect: 'follow'
};
fetch("https://uploads.github.com/repos/{OWNER}/{REPO}/releases/{ID}/assets?name=file.zip", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I'm not a technical person, so I can't code or anything, but I have to incorporate this API into google sheets.
Therefore I use this Javascript Code Sample in google Appscript. But There is no definition of the Headers.
var myHeaders = new Headers();
myHeaders.append("x-access-token", "<my gold api key>");
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://www.goldapi.io/api/XAU/EUR", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Can somebody tell me where I can find the Modul of the Headers Class and install it? Or is there another way to incorporate this API into google sheets?
Thank you for your Help!
Add these two lines at the top:
const fetch = require('node-fetch');
const { Headers } = fetch;
This is for Node-js. In a browser context your code would work without this, as the fetch API is included out of the box, and also Headers is defined.
I am trying to make a request to the REED jobs API although I am getting the error: TypeError: NetworkError when attempting to fetch resource. The call is being made in a React component. The Reed API states You will need to include your api key for all requests in a basic authentication http header as the username, leaving the password empty. This is the part that confuses me and I do not know how to configure the fetch in this way. To help with this, I have sent the API call from Postman and have managed to get response successfully. Because of this, I used the code generation function of Postman to make the below call, but it does not work:
var myHeaders = new Headers();
myHeaders.append("Authorization", `${process.env.REACT_APP_REED_KEY}==`);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
fetch("https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
Update:
I have changed the code to the below. Unfortunately, I am still getting an error. I am also now getting a new error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15. (Reason: CORS preflight response did not succeed).
Updated code:
import { encode } from "base-64";
var myHeaders = new Headers();
myHeaders.append("Authorization", `Basic ${encode(process.env.REACT_APP_REED_KEY)}`);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
fetch("https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));