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));
Related
I need to get access token from SharePoint, In order to upload some files!
I got access token from postman successfully, But when I try to do the same request with Javascript!
const generateToken = async () => {
const headers = { "Content-Type": "application/x-www-form-urlencoded" };
var formdata = {};
formdata["grant_type"] = "client_credentials";
formdata["client_id"] = "<client_id>";
formdata["client_secret"] = "<client_secret>";
formdata["resource"] =
"00000003-0000-0ff1-ce00-000000000000/site_url#tenant_id";
const body = Object.keys(formdata)
.map((key) => `${key}=${formdata[key]}`)
.join("&");
var requestOptions = {
method: "POST",
headers,
body,
};
await fetch(
"https://accounts.accesscontrol.windows.net/<tenant_id>/tokens/OAuth/2",
requestOptions
)
.then((response) => response.json())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
};
generateToken();
when I execute the page which have this script I got this error
error TypeError: Failed to fetch
at generateToken
But IDK why the respose status is 200 OK, without returning body which contain access_token
Any help is much appreciated!
You cannot get the token from javascript like that, only from single page applications because of the security issues: you expose your client secret.
You can use Microsoft Authentication Library (MSAL) for JS instead.
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
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 have created a Lambda function in python, inside this function I have put header with cross origin details. Here is the code of my Lambda function:
def lambda_handler(event, context):
data=''
s3_boto = boto3.client('s3')
s3 = boto3.resource('s3')
reference_elements = event['data1']
test_elements = event['data2']
try:
#access first event object
imagePath = []
data= compute_data(reference_elements, test_elements)
return response({'message': data}, 200)
except Exception as e:
return e
return response({'message': data}, 200)
def response(message, status_code):
return {
'statusCode': str(status_code),
'body': json.dumps(message),
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
}
Now I have created a AWS API Gateway with POST method and enable CORS. Then I deployed this API.
While I am running this API from Postman it is working fine.
But once I try to fetch this API from my React JS code it is throwing the following error:
enter image description here
Here is my React Js code in button click:
let postData = {"key1":"value1","key2":"value2","key3":"value3"}
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "*"
},
body: JSON.stringify(postData)
}
const url =
"https://apiId.execute-api.us-east-1.amazonaws.com/apiFunctionName"
fetch(url, requestOptions)
.then(response => console.log(response))
.then(data => console.log(data))
Please correct me where I am going wrong, I have invested lots of time for trial and error but no luck.
Browsers before making a call to a cross origin, makes a preflight request using the OPTIONS method. In your network tab, you should be seeing an OPTIONS call, which in your case is not allowed on ApiGateway. Similar to the POST method you have allowed on gateway, allow OPTIONS call. Return the OPTIONS call with a 200 and the CORS headers, based on which domain you want to allow.
I want to send data to my sever but I got this error:
TypeError: Failed to fetch
my codes:
function login(username, password) {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json','charset':'utf-8' },
body: JSON.stringify({ 'username':username , 'password':password })
};
console.log(requestOptions);
return fetch(BASE_URL+serverConstants.LOGIN_POST_REQUEST, requestOptions)
.then(response => {
if (!response.ok) {
return Promise.reject(response.statusText);
}
return response.json();
})
.then(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('user', JSON.stringify(user));
}
return user;
});
}
but I tested it on postman I got correct response.
Your preflight request is failing. Allow cross origin for the API you are hitting:
In node you do it like this,
res.header("Access-Control-Allow-Origin", "*");
Hope this helps
If you want to send values to your sever like form-data from postman sowftware you should use formData (your don't need to import FormData from any class):
var formData = new FormData()
formData.append('yourKey, 'yourValue');
var requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: formData
};
return fetch('Your url', options)
.then(checkStatus)
.then(parseJSON);
of course from your server-side you should enable CORS. CORS depending on your language server-side is different.