I am trying to show an image or a document coming from an AWS S3 Pre-Signed URL in my react application. Following is my code.
this.props.getS3SignedURL(key).then(url=> {
this.setState({ isLoading: false, error: "", url: url});
window.location = url;
}, err => {
//err
});
It works without any issue in Google Chrome, it displays the document. But in Microsoft Edge and IE the location doesn't change.
I tried with encodeURI(), encodeURIComponent() and window.location.href all combinations. But can't get it to work in Edge and IE. I tried with google document viewer as mentioned here. Still it's not working, and I suspect whether I can user Google document viewer because the document coming from the url can be an image/pdf/xls etc.
Based on your comment about unhandled promise rejection, one thing I'd recommend is try the more common method of handling errors of a promise, like below:
this.props.getS3SignedURL(key)
.then(url => {
this.setState({ isLoading: false, error: "", url: url });
window.location = url;
})
.catch(err => {
console.log(err);
});
Other then that, you may want to check that it's not a SOP issue or a CORS issue.
Related
I'm facing "TypeError: Failed to fetch" errors in my React App.
Depending on the url of the query I run I sometimes encounter the error, although the query does return a valid result when I test it in my browser.
Here are two examples with two sample URL:
(function(){
var GetRequestResult = function (url) {
return fetch(url, {
headers: { 'Access-Control-Allow-Origin': '*'}})
.then(response => response.text())
.then(text => console.log(text))
.catch(error => console.log(error))
};
this.GetRequestResult = GetRequestResult;
})(this);
console.log(GetRequestResult('https://jsonplaceholder.typicode.com/comments?postId=1')); // Works
console.log(GetRequestResult('http://api.plos.org/search?q=title:DNA')); // Returns 'TypeError: Failed to fetch'
So I have two questions:
Why the first one works and not the second ?
My final need is to retrieve a response from Google's Recaptcha API (https://developers.google.com/recaptcha/docs/verify) using the URL: https://www.google.com/recaptcha/api/siteverify . I am encountering the error on this url also.
I guess it's related to CORS (I tried to modify the Headers of my requests, to define https://www.google.com as a proxy, to use different methods to execute the requests ...) but without success. Any idea to solve this problem ?
The problem is solved.
I was trying to call the Google Recaptcha API (https://www.google.com/recaptcha/api/siteverify) from my frontend.
Due to Google's CORS policy this only seems possible from the backend side.
async function getRequest() {
fetch('https://api.plos.org/search?q=title:DNA')
.then( res => res.json())
.then( data => console.log(data.response.docs))
.catch( e => console.log(e))
}
The following code is working in nodejs
as instructed here https://cloudinary.com/documentation/advanced_url_delivery_options#client_side_resources
I used fetch API for accessing .json file to display uploaded media but an error occurs "Failed to load resource: the server responded with a status of 404 ()"
here's my code
useEffect(() => {
fetch(window.cloudinary.url("reactflix.json", {type: "list"}))
.then(res => res.json())
.then(
(result) => {
console.log(result)
},
(error) => {
console.log('error')
}
)
}, []);
I also have tried
useEffect(() => {
fetch('https://res.cloudinary.com/omama/image/list/reactflix.json')
.then(res => res.json())
.then(
(result) => {
console.log(result)
},
(error) => {
console.log('error')
}
)
}, []);
Client-side resources (aka Resource List) are restricted by default and require a Signed URL for access. Since you aren't using a Signed URL, the most likely reason for the 404 is that the setting inside your account is the default one hence this type is restricted.
You can check this by going to the Settings -> Security tab in your account and under the field "Restricted media types" ensure that the "Resource List" option is not checked. If it is, then you can uncheck that and Save the settings.
After doing that, you can test with a new tag which you haven't tested with before. This is because if the reason for the 404 was indeed the restriction then you may get a cached error response from Cloudinary. Testing with a new tag would ensure you don't run into this case.
Where did you find the cloud name "omama" and the tag "reactflix.json"?
You might want to check it.
Most times client-side requests are just simple URLs, so you don't need to check through your application, you could just access it in your browser but I recommend using Postman. If the URL doesn't return anything in your browser it counts as a 404.
I am trying to create a stripe payment app using reactJS and expressJS, I am getting this error:
Proxy error: Could not proxy request /payment from localhost:3000 to https://localhost:5000/
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (EPROTO)
In package.json file I have set proxy as -
"proxy": "https://localhost:5000"
In my react component I have -
const onToken = token => {
axios({
url: "payment",
method: "post",
data: {
amount: priceForStripe,
token: token
}
})
.then(response => {
alert("succesful payment");
})
.catch(error => {
console.log("Payment Error: ", error);
alert(
"There was an issue with your payment! Please make sure you use the provided credit card."
);
});
};
In my server.js I have -
const stripe = require("stripe")("sk_test_...");
app.post("/payment", (req, res) => {
const body = {
source: req.body.token.id,
amount: req.body.amount,
currency: "usd"
};
stripe.charges.create(body, (stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).send({ error: stripeErr });
} else {
res.status(200).send({ success: stripeRes });
}
});
});
whenever I submit any payment I hit error -
I tried all method linked here but can't solve that issue. I heartily thank if anyone explain any solution of that problem.
Since your backend works fine without stripe, the 500 error indicates that stripe is the problem.
This is related to the information you are sending in the body of the stripe charges.create request. I think you are missing the customer.id.
This post arjunphp.com/node-stripe-express-js shows the charges.create request as
{ amount,
description: "Sample Charge",
currency: "usd",
customer: customer.id
}
As #CherryDT mentioned, first I set proxy to "proxy": "http://localhost:5000". Then I change my backend code as #Greg M suggested -
app.post("/payment", (req, res) => {
stripe.customers
.create({
email: req.body.email, // customer email, which user need to enter while making payment
source: req.body.token.id // token for the given card
})
.then(customer =>
stripe.charges.create({
// charge the customer
amount: req.body.amount,
description: "Sample Charge",
currency: "usd",
customer: customer.id
})
)
.then(charge => res.status(200).send({ success: "success" }));
});
That's it. My payment method works perfectly.
I think the proxy error is a red herring. The real issue is the parsing on your server, causing the 500.
It looks like by default Axios encodes the json for you (but you should double check the request). To access JSON encoded request body data in Express, you need to use the body-parser middleware.
See this answer for an example: How do I consume the JSON POST data in an Express application
I'm taking the exact react course from Andre. My solution was to start the backend server.
So whoever gets into this issue from the same course either try the answer above or:
npm start
or
yarn start
I am trying to build a REST API for my server via CakePHP. I thought I had it working as I can receive the JSON responses via the web browser however when trying to access the same route via ReactJS, the Controllers Action is not actually firing.
Reading the CakePHP docs I really should only have to implement these lines of code to get the API working (According to the docs) and I did:
/config/routes.php
Router::scope('/', function($routes) {
$routes->setExtensions(['json']);
$routes->resources('Users');
});
Here is the API Endpoint I want to hit:
`public function signUp() {
$file = fopen("error_log.txt", "w");
$txt = "firing endpoint";
$fwrite($file, $txt);
$fclose($file);
$response = $this->response;
$responseText = [
"status" => "200",
"message" => "User added successfully"
];
$response = $response->withType("application/json")
->withStringBody(json_encode($responseText));
return $response;
}`
Here I am successfully hitting that endpoint via the browser. My log message also appears in the error_log.txt file
Here is where I'm making a request via ReactJS:
handleRequest = () => {
console.log('making request');
axios({
method: 'get',
url: 'https://157.230.176.243/users/register.json',
data: {
email: this.state.email,
password: this.state.password
}
})
.then(function(response) {
console.log('got response');
console.log(response);
})
.catch(function(error) {
console.log('got error');
console.log(error);
})
.then(function(data) {
console.log('always executed');
console.log(data);
});
}
When I make this request via ReactJS I get a XHR failed loading: OPTIONS "https://157.230.176.243/users/register.json"
Also when making this request via ReactJS my log message does not get written to error_log.txt
Ok I finally figured out what was wrong. I have my React Development server running on
157.230.176.243:3001
and my CakePHP API served on that same server,
157.230.176.243
React didn't like it that I was passing the full URL of the API to the fetch()
call. I switched my React code to
url: "/users/register.json"
and it works fine.
I am submitting a form generated using HTML5(in ReactJs) and the data of which I am sending to a REST service using POST request.
submitForm = event => {
event.preventDefault();
axios({
method: "post",
url: "http://localhost:8080/signup",
data: this.formData //formData is an object which contains form data
}).catch(error => {
this.setState({
isError: true,
errorMessage: error.response.data.errors[0].message
});
});
};
Here, errorMessage is the state object which will be printed to the UI as an alert box.
Now, on my system, when I am submitting the form I am getting the alert box perfectly, but when I submitting the same data from chrome on my android device, I am getting this below error:
Unhandled Rejection (TYpeError): Cannot read property 'data' of undefined
I am quite surprised why data is a valid object on macOS browser then.
Any suggestions please.