404 when making a get request with axios - react-native

I'm getting a 404 request for this:
import axios from "axios";
axios
.get("https://api-public.sandbox.pro.coinbase.com")
.then((data) => console.log(data.json()));
The error:
Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
createError # createError.js:16
settle # settle.js:17
handleLoad # xhr.js:61
Promise.then (async)
(anonymous) # App.js:75
invokePassiveEffectCreate # react-dom.development.js:23487
callCallback # react-dom.development.js:3945
invokeGuardedCallbackDev # react-dom.development.js:3994
invokeGuardedCallback # react-dom.development.js:4056
flushPassiveEffectsImpl # react-dom.development.js:23574
unstable_runWithPriority # scheduler.development.js:468
runWithPriority$1 # react-dom.development.js:11276
flushPassiveEffects # react-dom.development.js:23447
(anonymous) # react-dom.development.js:23324
workLoop # scheduler.development.js:417
flushWork # scheduler.development.js:390
performWorkUntilDeadline # scheduler.development.js:157
It's because of cors. What is the best way to fix this?
It's because of cors. What is the best way to fix this?

Use this server https://cors-anywhere.herokuapp.com/ as a proxy on your request, it solved it for me, for more detail on it click here
or you can try using the fetch api
I'd recommend, you use a catch on that Axios request to get more details on the error

Try below code;
import axios from 'axios';
//Create Axios instance
const Instance = axios.create({
baseURL: "https://api-public.sandbox.pro.coinbase.com",
timeout: 15000,
timeoutErrorMessage: 'Your request Timed-out',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }
});
//Export the Instance if needed
//From a function, use the instance
Instance.get("")
.then((data) => console.log(data.json()));

Related

Why am I getting 3 "Cross-Origin Request Blocked" messages

I have a Svelte application and I am trying to render data from the API but I keep on getting 3 error messages.
The code works properly on node but not on Svelte.
Below is the Svelte code:
<script lang="ts">
import { onMount } from "svelte";
let word = [];
onMount(async () => {
const response = await fetch(
"https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5",
{
method: "GET",
headers: {
"X-RapidAPI-Key": "KEY",
"X-RapidAPI-Host": "random-words5.p.rapidapi.com",
},
}
);
word = await response.json();
console.log(word);
});
</script>
<p>{word}</p>
And below are the error messages:
ross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://localhost:5173’).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5. (Reason: CORS request did not succeed). Status code: (null).
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
How do I get my code to render out the data from the API in Svelte?
The CORS issue occurs when you try to fetch a resource from a local environment, this is the case when you run your app in dev mode.
I use the CORS Unblock extension to fix the issue, give it a try.

Inconsistent behavior from react-native-blob-util and fetch

I'm trying to call an API that takes an image and some data and returns json. I'm using react-native-blob-util with fetch. Problem is, the same code is working sometimes but failing in the next attempt - almost every alternate request is not submitting the data.
For replicating the issue, I have created the following code. It takes the **same** image file and parameters to make a fetch request.
(I am testing on android)
A button to call fetch function:
<TouchableOpacity
style={styles.btn}
onPress={() => {
MatchFace();
}}
>
<Text style={styles.btnText}>
Call API
</Text>
</TouchableOpacity>
And then this is the function that calls API:
const MatchFace = async () => {
setData([]);
ReactNativeBlobUtil.fetch(
'POST',
'url_for_the_api',
{
'Content-Type': 'multipart/form-data',
'Api-Key': 'api_key',
},[
{ name : 'image', filename : 'profile.jpg', type:'image/jpg', data: ReactNativeBlobUtil.wrap(decodeURIComponent('file:///storage/emulated/0/Download/profile.JPG'))},
{ name : 'album_id', data : '2'},
]
)
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => console.log(data));
}
Part of log
**No response case**
G:\react-native\FaceAttendance\Screens\stackOverFlow.js:52 []
**Case where I get response**
G:\react-native\FaceAttendance\node_modules\react-native\Libraries\LogBox\LogBox.js:173 Stream Closed
registerWarning # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\LogBox\LogBox.js:173
console.warn # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\LogBox\LogBox.js:71
overrideMethod # G:\react-native\FaceAttendance\node_modules\react-devtools-core\dist\backend.js:2171
(anonymous) # G:\react-native\FaceAttendance\node_modules\react-native-blob-util\fetch.js:15
emit # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\vendor\emitter\_EventEmitter.js:149
__callFunction # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:419
(anonymous) # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:116
__guard # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:370
callFunctionReturnFlushedQueue # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:115
(anonymous) # RNDebuggerWorker.js:2
G:\react-native\FaceAttendance\node_modules\react-native\Libraries\LogBox\LogBox.js:173 Stream Closed
registerWarning # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\LogBox\LogBox.js:173
console.warn # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\LogBox\LogBox.js:71
overrideMethod # G:\react-native\FaceAttendance\node_modules\react-devtools-core\dist\backend.js:2171
(anonymous) # G:\react-native\FaceAttendance\node_modules\react-native-blob-util\fetch.js:15
emit # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\vendor\emitter\_EventEmitter.js:149
__callFunction # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:419
(anonymous) # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:116
__guard # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:370
callFunctionReturnFlushedQueue # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:115
(anonymous) # RNDebuggerWorker.js:2
G:\react-native\FaceAttendance\node_modules\react-native\Libraries\Core\ExceptionsManager.js:149 Error: unexpected end of stream
at G:\react-native\FaceAttendance\node_modules\react-native-blob-util\fetch.js:256
at MessageQueue.__invokeCallback (G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:465)
at G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:127
at MessageQueue.__guard (G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:370)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:126)
at RNDebuggerWorker.js:2
reactConsoleErrorHandler # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\Core\ExceptionsManager.js:149
registerError # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\LogBox\LogBox.js:204
console.error # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\LogBox\LogBox.js:67
overrideMethod # G:\react-native\FaceAttendance\node_modules\react-devtools-core\dist\backend.js:2171
eval # G:\react-native\FaceAttendance\Screens\stackOverFlow.js:51
tryCallOne # G:\react-native\FaceAttendance\node_modules\promise\setimmediate\core.js:37
(anonymous) # G:\react-native\FaceAttendance\node_modules\promise\setimmediate\core.js:123
(anonymous) # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:248
_callTimer # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:112
_callReactNativeMicrotasksPass # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:166
callReactNativeMicrotasks # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:418
__callReactNativeMicrotasks # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:393
(anonymous) # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135
__guard # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:370
flushedQueue # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134
invokeCallbackAndReturnFlushedQueue # G:\react-native\FaceAttendance\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:130
(anonymous) # RNDebuggerWorker.js:2
G:\react-native\FaceAttendance\Screens\stackOverFlow.js:52 {num_faces: 1, num_recognized_faces: 1, num_unknown_faces: 0, recognized_faces: Array(1), unknown_faces: Array(0)}
I'm sure that API is performing correctly (tested from test apps on react, php and also postman). I'm possibly doing something wrong with the react-native filesytem.
Oh, one more input - my application needs to call this API in every few seconds when the app runs.

Vue.js - CORS error in local and production

I have got a file that's name is request.js,
import axios from 'axios'
const baseURL = 'https://SOME_URL.com/api/'
const config = {
baseURL,
timeout: 10000,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
}
}
const request = axios.create(config)
export default request
and I'm trying to send request in Vuex Actions;
import request from '../request'
const actions = {
postData(_, payload){
return request.post('a-request-url', payload)
}
}
Sending 2 requests and throws a CORS error when I run request. CORS error Access to XMLHttpRequest at 'https://crm.clinic/api/crm/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
AND 2 requests like;
and the real problem, cors error continious when deploy my code as production. Can you help me?
If you read the second part in the error it says where the issue is.
Request header field access-control-allow-origin is not allowed by
Access-Control-Allow-Headers in preflight response
As you can see you need to allow access in preflight response. A preflight request is something the browser does before sending your actual GET/POST/etc request. In the devtools' network tab you have 2 requests for the /login url. First one is a preflight using OPTIONS method.
To fix the issue you need to make sure your backend server returns 'Access-Control-Allow-Origin': 'http://localhost:8080' header in it's response for OPTIONS requests. Currently it is specifying only allowed methods and headers. You don't need to add those headers to your axios request.

How do I fix Malformed authentication header error coming from Apollo client

I'm trying to connect my react app to a hasura backend api with Apollo Client, but I recieve the following error:
Error: GraphQL error: Malformed Authorization header
I have no idea what is causing it.
I know I'm getting a valid id token from Cognito because I can paste it into the Hasura console and it works fine.
I really just pasted the apollo authorization example into my index.js file and put in my uri. I started out using apollo-boost, but went to apollo-client because of the same error. It didn't help, obviously. I've scoured the internet and can't find anything that seems to relate to this, which probably means I'm doing something stupid.
Here's my apollo-client code from my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import ApolloClient from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloProvider } from 'react-apollo';
import { Auth } from 'aws-amplify';
async function getSession() {
Auth.currentSession().then(res=>{
let idToken = res.getIdToken()
let jwt = idToken.getJwtToken()
//if I console log jwt here I can paste it into hasura and it works
return jwt
})
}
const token = getSession()
//copied from apollo docs:
const httpLink = createHttpLink({
uri: 'https://api.example.com/v1/graphql',
});
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
here's the error:
Error: GraphQL error: Malformed Authorization header
at new ApolloError (bundle.esm.js:76)
at ObservableQuery.getCurrentResult (bundle.esm.js:200)
at ObservableQuery.currentResult (bundle.esm.js:163)
at Query._this.getQueryResult (react-apollo.esm.js:247)
at finish (react-apollo.esm.js:434)
at Query.render (react-apollo.esm.js:441)
at finishClassComponent (react-dom.development.js:15319)
at updateClassComponent (react-dom.development.js:15274)
at beginWork (react-dom.development.js:16262)
at performUnitOfWork (react-dom.development.js:20279)
at workLoop (react-dom.development.js:20320)
at renderRoot (react-dom.development.js:20400)
at performWorkOnRoot (react-dom.development.js:21357)
at performWork (react-dom.development.js:21267)
at performSyncWork (react-dom.development.js:21241)
at requestWork (react-dom.development.js:21096)
at scheduleWork (react-dom.development.js:20909)
at Object.enqueueForceUpdate (react-dom.development.js:11632)
at Query.push../node_modules/react/cjs/react.development.js.Component.forceUpdate (react.development.js:355)
at Query._this.updateCurrentData (react-apollo.esm.js:214)
at Object.error (react-apollo.esm.js:197)
at notifySubscription (Observable.js:157)
at onNotify (Observable.js:196)
at SubscriptionObserver.error (Observable.js:253)
at bundle.esm.js:541
at Array.forEach (<anonymous>)
at iterateObserversSafely (bundle.esm.js:540)
at Object.onError [as error] (bundle.esm.js:482)
at invoke (bundle.esm.js:1532)
at bundle.esm.js:1565
at bundle.esm.js:1986
at Set.forEach (<anonymous>)
at bundle.esm.js:1984
at Map.forEach (<anonymous>)
at QueryManager.broadcastQueries (bundle.esm.js:1982)
at bundle.esm.js:2109
at Object.next (Observable.js:333)
at notifySubscription (Observable.js:152)
at onNotify (Observable.js:196)
at SubscriptionObserver.next (Observable.js:248)
at bundle.esm.js:1079
at Set.forEach (<anonymous>)
at Object.next (bundle.esm.js:1078)
at notifySubscription (Observable.js:152)
at onNotify (Observable.js:196)
at SubscriptionObserver.next (Observable.js:248)
at notifySubscription (Observable.js:152)
at onNotify (Observable.js:196)
at SubscriptionObserver.next (Observable.js:248)
at bundle.esm.js:107
Plus I get errors from the browser because the query didn't return anything.
Here's what chrome console has in the graphql header:
General:
Request URL: https://api.example.com/v1/graphql
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: 137.242.2.135:8080
Referrer Policy: no-referrer-when-downgrade
Response:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: authorization,content-type
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE,OPTIONS
Access-Control-Allow-Origin: https://example.com
Access-Control-Max-Age: 1728000
Content-Type: text/plain charset=UTF-8
Date: Thu, 18 Jul 2019 17:42:21 GMT
Server: Caddy, Warp/3.2.27
Request
Provisional headers are shown
Access-Control-Request-Headers: authorization,content-type
Access-Control-Request-Method: POST
Origin: https://example.com
Referer: https://example.com/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
Any help would be appreciated.
The value assign to token is of type Promise and not a string as you expect.
Since getSession() is an async function, therefor it returns a promise.
This line:
const token = getSession()
assigns the promise and not its resolved value to the token.
You need to wait for the promise to resolve before assigning the result to token.

HTTP post working on postman but not on Angular 2

I have a template which (click) triggets addUseCase():
import {Component} from "#angular/core";
import {DataService} from "../shared/data.service";
import {Config} from "../shared/strings";
import {Headers, Http} from "#angular/http";
#Component({
selector: "add",
styleUrls: ["add.component.scss"],
templateUrl: "add.component.html"
})
export class AddComponent {
public title: string;
public body: string;
constructor(private dataService: DataService,
private http: Http) {
this.title = "";
this.body = "";
}
public addUseCase() {
let url = Config.baseUrl + Config.case;
console.log("url", url); // --> http://localhost:3001/case
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let body = JSON.stringify({title:this.title})
this.http.post(url, body, {headers: headers}).map( res => console.log ("res", res), error => console.log("error", error));
}
}
After testing in Postman I get my node/express server correct response. But when I try to use angular HTTP to send I don't get any response at all, no error:
My postman works, but can't make http post of angular 2 work:
Update with errors:
this.http.post(url, body, {headers: headers})
.map(res => res.json()).subscribe(data => console.log(data)); //...errors if any
;
And the errors:
EXCEPTION: Unexpected token W in JSON at position 0ErrorHandler.handleError # core.umd.js:3462next # core.umd.js:6924schedulerFn # core.umd.js:6172SafeSubscriber.__tryOrUnsub # Subscriber.js:223SafeSubscriber.next # Subscriber.js:172Subscriber._next # Subscriber.js:125Subscriber.next # Subscriber.js:89Subject.next # Subject.js:55EventEmitter.emit # core.umd.js:6164onError # core.umd.js:6388onHandleError # core.umd.js:6263ZoneDelegate.handleError # zone.js:236Zone.runTask # zone.js:157ZoneTask.invoke # zone.js:335
core.umd.js:3467 ORIGINAL STACKTRACE:ErrorHandler.handleError # core.umd.js:3467next # core.umd.js:6924schedulerFn # core.umd.js:6172SafeSubscriber.__tryOrUnsub # Subscriber.js:223SafeSubscriber.next # Subscriber.js:172Subscriber._next # Subscriber.js:125Subscriber.next # Subscriber.js:89Subject.next # Subject.js:55EventEmitter.emit # core.umd.js:6164onError # core.umd.js:6388onHandleError # core.umd.js:6263ZoneDelegate.handleError # zone.js:236Zone.runTask # zone.js:157ZoneTask.invoke # zone.js:335
core.umd.js:3468 SyntaxError: Unexpected token W in JSON at position 0
at JSON.parse (<anonymous>)
at Function.Json.parse (http://localhost:3000/vendor.bundle.js:11272:59)
at Response.Body.json (http://localhost:3000/vendor.bundle.js:12250:30)
at MapSubscriber.project (http://localhost:3000/main.bundle.js:6202:47)
at MapSubscriber._next (http://localhost:3000/vendor.bundle.js:23914:36)
at MapSubscriber.Subscriber.next (http://localhost:3000/vendor.bundle.js:249:19)
at XMLHttpRequest.onLoad (http://localhost:3000/vendor.bundle.js:12581:43)
at ZoneDelegate.invokeTask (http://localhost:3000/polyfills.bundle.js:14882:36)
at Object.onInvokeTask (http://localhost:3000/vendor.bundle.js:6930:42)
at ZoneDelegate.invokeTask (http://localhost:3000/polyfills.bundle.js:14881:41)
------------- Elapsed: 16 ms; At: Thu Oct 27 2016 08:06:32 GMT-0500 (COT) -------------
at Object.onScheduleTask (http://localhost:3000/polyfills.bundle.js:14537:19)
at ZoneDelegate.scheduleTask (http://localhost:3000/polyfills.bundle.js:14859:50)
at Zone.scheduleEventTask (http://localhost:3000/polyfills.bundle.js:14791:40)
at zoneAwareAddListener (http://localhost:3000/polyfills.bundle.js:15441:15)
at XMLHttpRequest.addEventListener (eval at createNamedFn (http://localhost:3000/polyfills.bundle.js:15544:18), <anonymous>:3:43)
at Observable._subscribe (http://localhost:3000/vendor.bundle.js:12624:23)
at Observable.subscribe (http://localhost:3000/vendor.bundle.js:70:28)
at Observable._subscribe (http://localhost:3000/vendor.bundle.js:128:29)ErrorHandler.handleError # core.umd.js:3468next # core.umd.js:6924schedulerFn # core.umd.js:6172SafeSubscriber.__tryOrUnsub # Subscriber.js:223SafeSubscriber.next # Subscriber.js:172Subscriber._next # Subscriber.js:125Subscriber.next # Subscriber.js:89Subject.next # Subject.js:55EventEmitter.emit # core.umd.js:6164onError # core.umd.js:6388onHandleError # core.umd.js:6263ZoneDelegate.handleError # zone.js:236Zone.runTask # zone.js:157ZoneTask.invoke # zone.js:335
http.umd.js:188 Uncaught SyntaxError: Unexpected token W in JSON at position 0(…)Json.parse # http.umd.js:188Body.json # http.umd.js:1166(anonymous function) # add.component.ts:34MapSubscriber._next # map.js:77Subscriber.next # Subscriber.js:89onLoad # http.umd.js:1497ZoneDelegate.invokeTask # zone.js:265onInvokeTask # core.umd.js:6233ZoneDelegate.invokeTask # zone.js:264Zone.runTask # zone.js:154ZoneTask.invoke # zone.js:335
You never subscribed to the Observable. No request will be made until you do so
this.http.post(url, body, {headers: headers})
.map(res => res.text()).subscribe(data => console.log(data));