I'm having a hard time getting a good response from the tumblr api on a GULP localhost.
using postman, I get the proper response from the request URL:
http://api.tumblr.com/v2/blog/{any_blog}/posts?limit=5&api_key={key}
I can't seem to get the response in my aurelia module though. I keep getting the error
Fetch API cannot load http://api.tumblr.com/...........
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access.
Code is below:
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';
#inject(HttpClient)
export class Users{
heading = 'Blog Posts';
posts = [];
constructor(http){
http.configure(config => {
config
.withBaseUrl('http://api.tumblr.com/v2/')
.withDefaults({
headers: {
'Access-Control-Allow-Origin': '*'
}
});
});
this.http = http;
}
activate(){
return this.http.fetch('blog/{blog_name}.tumblr.com/posts', { limit: 5, api_key: {api_key} })
.then(response => response.json())
.then(posts => this.posts = posts);
}
}
This is CORS limitation. You can't make cross-domain requests if your origin is not granted permission. It works for server-side requests of course, that's why you can fetch data without problem in case of nodejs request.
To workaroud the problem you should make use of JSONP approach supported by Tumblr. You would also use HttpClient for jsonp method.
In your case code will be:
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
#inject(HttpClient)
export class Users{
heading = 'Blog Posts';
posts = [];
constructor(http){
http.configure(config => {
config
.withBaseUrl('http://api.tumblr.com/v2/')
.withParams({
limit: 5,
api_key: '{api_key}'
});
});
this.http = http;
}
activate(){
return this.http.jsonp('blog/{blog_name}.tumblr.com/posts', 'jsonp')
.then(httpResponse => this.posts = httpResponse.response.response.posts);
}
}
Related
I have following react code to make call to django rest framework API:
import Cookies from 'js-cookie';
import axios from "axios";
async downloadVideowiseCSV (fromDate, toDate) {
var url = '/stat/getStats/';
const axiosInstance = axios.create();
try {
const response = await axiosInstance.post(url,
{
data: {
'format': 'json'
},
header: {
'X-CSRFToken': Cookies.get('csrftoken')
}
}
)
//...
}
When this method gets called, the corresponding request fails with CSRF verification:
However when I check the payload of the request, I could see that X-CSRFTOken is indeed populated:
Then whats going wrong here?
The problem is in your axios request, it's not correct to send the header in the body of the HTTP request.
The following should be a valid axios request which separates the data from the options
ex:
const config = {
headers: { 'X-CSRFToken': Cookies.get('csrftoken') },
};
const data = {format: 'json'}
axios.post('http://YOUR_URL', data, config)
.then((response) => {
console.log(response.data);
});
I'm using axios in an application Nextjs where I use the Youtube API and the following error occurred
Below is the code
import React from "react";
import youtube from "./api";
import VideoList from "./VideoList";
class App extends React.Component {
state = {
videos: [],
};
componentDidMount() {
this.onTermSubmit("Car");
}
onTermSubmit = async (term) => {
const res = await youtube.get("/search", {
params: {
q: term,
},
});
this.setState({ videos: res.data.items });
};
render() {
return (
<>
<div>
<div >
<VideoList
videos={this.state.videos}
/>
</div>
</div>
</>
);
}
}
export default App;
The other
import axios from 'axios';
const KEY = "xxxxx";
export default axios.create({
baseURL: "https://www.googleapis.com/youtube/v3",
params: {
part: "snippet",
maxResults: 16,
key: KEY,
},
});
I would like a tip on how to solve this and if the best solution would be to change from Axios to fetch. Problem is, I don't know how to change from Axios to fetch.
I dont think that is related to package. Because 403 is forbidden response status code which indicates that the server understands the request but refuses to authorize it. Most likely you pass the wrong api key. If you need to fetch the data with fetch, you can write a reusable function:
// genre is like video type. for example Productivity
const videos = async (genre) => {
const YOUTUBE_API_KEY = process.env.YOUTUBE_API_KEY;
const BASE_URL = "youtube.googleapis.com/youtube/v3";
const response = await fetch(
`https://${BASE_URL}/${genre}&maxResults=25&key=${YOUTUBE_API_KEY}`
);
return await response.json();
};
this is from docs
Received a 401 or 403 error
If you're getting a 401 or 403 error when testing a sample, it's likely due to a problem with one of the following:
The API isn't enabled for your project. Review instructions for your API on how to create a project and enable an API.
You're using the wrong authorization type (API key instead of OAuth 2.0).
You're using OAuth 2.0, but with too narrow a scope.
When you set up your API key, you set up restrictions to prevent unauthorized use of your credentials. However, the request isn't meeting those restrictions.
Downgrade to AXIOS 0.26.0
Probably you are using last version automatically.
Related:
https://github.com/axios/axios/issues/4638
This question already has an answer here:
Access to XMLHttpRequest at 'https://api-v3.igdb.com/games...' ... No 'Access-Control-Allow-Origin' header is present on the requested resource
(1 answer)
Closed 1 year ago.
Despite this being a very common problem, the solutions I've searched don't seem to fix this for me.
import React from "react";
import axios from "axios";
class GamesList extends React.Component {
componentDidMount = async () => {
const response = await axios.get("https://api-v3.igdb.com/games", {
headers: {
"user-key": "<API-KEY>",
"Access-Control-Allow-Origin": "http://localhost:3000",
},
});
console.log(response);
};
render() {
return <div>MANY GAMES</div>;
}
}
export default GamesList;
The error messages I receive from running this code is:
Access to XMLHttpRequest at 'https://api-v3.igdb.com/games' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET https://api-v3.igdb.com/games net::ERR_FAILED
uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
I've also tried setting "Access-Control-Allow-Origin": "*" though the error doesn't change.
Is there a simple fix for this that doesn't require using/creating a proxy?
--- UPDATE ---
following #HMR's comment, I've edited the code below as per igdb's documentation, though I'm still getting the same error. Where am I going wrong with this?
import React from "react";
import axios from "axios";
class GamesList extends React.Component {
componentDidMount = async () => {
// As mention in the docs, I'm using POST with the necessary body
axios.post("https://api-v3.igdb.com/headers", {
body: {
api_header: {
header: "Access-Control-Allow-Origin",
value: "*",
},
},
});
// now to make the actual request
const response = await axios.get("https://api-v3.igdb.com/games", {
headers: {
"user-key": "<API-KEY>",
"Access-Control-Allow-Origin": "http://localhost:3000",
},
});
console.log(response);
};
render() {
return <div>MANY GAMES</div>;
}
}
export default GamesList;
Even posting the following to https://api-v3.igdb.com/headers/ inside of postman returns Not found:
{
"api_header": {
"header": "Access-Control-Allow-Origin",
"value": "*"
}
}
-- FINAL UPDATE --
As #goto1 and #HMR have mentioned below, the api itself doesn't seem to support CORS correctly.
I've ended up going with a proxy in the end! I'm using https://github.com/Rob--W/cors-anywhere/ (NOTE: I had to npm install proxy-from-env manually)
After starting up the server using node server.js, I can prepend the server's address to my igdb api request. Final code:
import React from "react";
import axios from "axios";
class GamesList extends React.Component {
componentDidMount = async () => {
const response = await axios.get("http://0.0.0.0:8080/https://api-v3.igdb.com/games", {
headers: {
"user-key": "<API-KEY>",
},
});
console.log(response); // WORKS!
};
render() {
return <div>MANY GAMES</div>;
}
}
export default GamesList;
Did you try ti set localhost:3000 in package.json instead in axios headers
I am developing an application with Ionic Framework Version 3.19.1, I am making a request via post, the URL data, and necessary parameter information is all ok, however, it is returning an error that I can not solve, I have tried many ways, imports into the project, but without success. below is my post function.
const req = this.http.post(url, {
options: {
headers:[header],
params:[postData]
}
}).subscribe(
res => {
console.log(res);
},
err => {
console.log('Ocorreu um erro');
}
)
Below are my imports inside the .ts file (TypeScript)
import { Component } from '#angular/core';
import { TranslateService } from '#ngx-translate/core';
import { IonicPage, NavController, ToastController } from 'ionic-angular';
import { HttpClient, HttpParams, HttpHeaders, HttpErrorResponse } from '#angular/common/http';
import { IonicStorageModule } from '#ionic/storage';
import { User } from '../../providers/providers';
import { MainPage } from '../pages';
Well, as I said I'm doing a post request and on the console, it returns an OPTIONS 500 (Internal Server Error)
Failed to load (URL): Response to preflight request does not pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 8100' is therefore not allowed access. The response had HTTP status code 500.
by what I understand is reporting a problem regarding the Header, but I have already informed the correct one and left the requests open, but it still does not work, here is my header below.
const header = new HttpHeaders();
header.set('Access-Control-Allow-Origin', '*');
header.set('Content-type', 'application/json');
change the const req
return new Promise((resolve, reject) => {
this.http.post(url, postData,
{headers: this.header})
.subscribe(
data => {
console.log('success');
resolve(data);
},
err => {
reject(err);
console.log(err);}
);
});
This is my full code...
this.http.post(link, data, { headers: headers })
.map(res => res.json())
.subscribe(data => {
this.data.response = data._body;
}, error => {
console.log("Oooops!");
});
after running the code this error is present:
"XMLHttpRequest cannot load
https://script.google.com/macros/s/AKfycbzdHHKBmLWJYZtFGlJGOrUwlPIWXor1geEOgcSgvhs/dev.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8100' is therefore not allowed access.
The response had HTTP status code 401."
I've searched about CORS... but I can't get my head around it...
Any help will be appreciated.
i have same issue but after some hours to search my problem gone.
ionic.config.json
{
"name": "KickStarter",
"app_id": "85ff0666",
"v2": true,
"typescript": true,
"proxies": [
{
"path": "/mobile",
"proxyUrl": "http://xxxxx:port/mobile"
}
]
}
you should use ionic g provider [name-of-provider] --ts it will generate provider to make a request like this:
export class AuthProvider {
data: any = null;
constructor(public http: Http) { }
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise wi new data.
this.http.get('/mobile/api/authentication')
.map(res => res.json())
.subscribe(data => {
// we've got back the raw data, now generate the core schedule data
// and save the data for later reference
resolve(this.data);
});
});
}
}
just remember: /mobile/api/authentication -> /mobile from path in ionic.config.json.
Download the Allow-Control-Allow-Origin application from google chrome. Enable the CORS in the application installed and execute your code. This will temporarily allow the CORS in your browser.