Using JSONP in react-redux application - reactjs

I am just trying to get the CORS headers issue caused by missing headers in request out of the way and hence inclined to using JSONP.
Any suggestions/ideas how to use JSONP in a react-redux app? Like how to configure and use it?

In your react component, dispatch an action that is caught by middleware. The middleware should make a call to the jsonp endpoint, probably using jquery's $.ajax method. I also like the fetchJsonp library. Your middleware should then dispatch a new action with the data received by ajax or fetchJsonp, which should be caught by your reducer, and alter the state.

I use fetch in most of cases in react apps:
// payload is your post data
const payload = {data: 'test'};
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
cors: true, // allow cross-origin HTTP request
credentials: 'same-origin' // This is similar to XHR’s withCredentials flag
};
// SEND REQUEST
fetch('http://example.com/', options).then((response) => {
// TODO
}).catch((error) => {
// TODO
});

Related

React async call to API not returning when non successful

I make a call to an API using the Amplify API:
import { API } from 'aws-amplify'
await API.get('myapi', 'endpoint')
.then(data => {
// Do something here
})
When my API returns 200 and some data back, then the then body is executed successfully. The problem is, when the endpoint returns 404 (or better non-200 response), it seems like the await API.get .... is not returning and therefore the then body is never executed. I can see in the developer tools and in the Network tab that the call indeed returned a 404 error, it's just in React it never triggers the then body.
This is what the API returns:
return {
'statusCode': 404,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers' : 'Content-Type',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET'
}
}
.then() is triggered when your request is successful and .catch() is triggered when request is rejected.
import { API } from 'aws-amplify'
await API.get('myapi', 'endpoint')
.then(data => {
// Do something here
})
.catch((err) => {
console.log(err);
});
Plus, I don't think using await along with .then() is a good practice.
.then().catch() and async/await are 2 popular ways of handling asynchronous executions.They should not be mixed with each other.
Reference link : https://www.geeksforgeeks.org/difference-between-promise-and-async-await-in-node-js/?ref=lbp

AWS Amplify CLI API PUT call and check response status in ReactJS

I have a REST API on AWS which calls a lambda function to update something in the database. It can return either 200 (success) or other errors. In my React app, I want to make a PUT call to the API and check the status once it returns.
Here is the response from the lambda:
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers' : 'Content-Type',
'Access-Control-Allow-Origin': 'http://localhost:3000',
'Access-Control-Allow-Methods': 'PUT'
}
}
Here is what I have so far:
import { API } from 'aws-amplify'
async function onButtonClick() {
const response = await API.put('myapi', 'endpoint')
if(response['statusCode'] === 200){
console.log("Completed!")
}
}
However, although the request to the API is sent, and the database is updated, in my React app it never triggers that if statement. Checking the response by logging it to the console it looks like an empty string?

Getting the React CORS preflight error in React Native

I am getting the CORS access error in my React Native app when connecting to an external API.
async componentDidMount() {
// POST request using fetch with async/await
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: JSON.stringify({ type:'accountLookup',storeId:STORE_ID, storeKey:STORE_KEY, memberId:'471324' })
};
const response = await fetch('http://frequent5.revlogical.com/wsMobile', requestOptions);
const data = await response.json();
this.setState({ data: data });
The problem is most likely not with React app, rather with your server which is not configurated to serve your app.
You should set 'Access-Control-Allow-Origin' header on your server to allow your app's address to make requests.
This problem is usually the fault of the backend. Test it with a tool like https://www.test-cors.org/
An alternative is to create a server to be intercepted between the frontend and the API, and you can handle this guy's cors

How do I trigger an action after API call using redux-api-middleware

I am trying to use redux-api-middleware. I would like my app to POST a sign up request to an API and once it receives a response, trigger a function, similar to a .then() function. Something like this:
export const signUp = (user, functionToClearForm) => ({
[RSAA]: {
endpoint: '/api/users/',
method: 'POST',
body: JSON.stringify(user),
headers: {'Content-Type': 'application/json'},
types: [
SIGNUP_REQUEST, SIGNUP_SUCCESS, SIGNUP_FAILURE
]
}
.then(functionToClearForm());
})
How do I do this? Is there any example or tutorial explaining how to trigger an action AFTER the API call is made. The only tutorials I found show how to update the state, but I don't want to update the state, I want to trigger an action.
Can this even be done use RSAA?
You should use redux-thunk or redux-saga to make async calls.

Fetch request to Cloudinary API from with React Component fails

I want to make an HTTP request to the Cloudinary API for pictures in my account. The url necessary looks like this:
https://<<API KEY>>:<<API SECRET>>#api.cloudinary.com/v1_1/<<RESOURCE NAME>>/resources/image
and when I hit this url from the browser, I get what I'm looking for, a beautiful JSON object with all my pictures.
But when I hit the url from within a React component,
componentDidMount() {
this.props.fetchArt();
}
I get the following error:
TypeError: Failed to execute 'fetch' on 'Window': Request
cannot be constructed from a URL that includes credentials:
The action creator looks like
export function fetchArt() {
const url = 'https://'+CLOUDINARY_KEY+':'+CLOUDINARY_SECRET+'#api.cloudinary.com/v1_1/prints20/resources/image';
const request = fetch(url).then(res => res.json())
return {
type: FETCH_ART,
payload: request
}
}
Link to the repo: https://github.com/PantherHawk/prints20-2018
Thanks a million in advance!
If your endpoint requires some sort of authorization you'll need to pass that info inside the headers of your request.
Cloudinary Authentication is done using Basic Authentication over secure HTTP. Your Cloudinary API Key and API Secret are used for the authentication.
fetch('https://api.cloudinary.com/v1_1/CLOUD_NAME/resources/image', {
method: 'get',
headers: {
'Authorization': 'Basic ' + base64.encode(API_KEY + ":" + API_SECRET),
},
}).then(res => res.json())

Resources