Spring method with React front - reactjs

Hi i'm trying to create small project with React Front and Spring Java backend.
Let's say in Spring Controller class i have a method:
#CrossOrigin(origins = "http://localhost:3000/")
#GetMapping("/something")
public void printSomething()
{
System.out.println("examplePhrase");
}
In React i have a form with button that invoke method 'handleSpring' looks like:
handleSpring = e =>
{
e.preventDefault();
console.log("Method started");
const SpringAPI = `http://localhost:8080/something`
fetch(SpringAPI, {})
.then(response => console.log("method works"))
.catch(err => console.log("method failed"))
}
When i run both application and go to "localhost:8080/something" i have a message in Intellij console "examplePhrase" so Spring method works. When i'm going to "localhost:3000", i have my form made by React. But when i right-click on this site, choose "inspect" -> "console" in browser menu, and next press form button i have an error:
method started
localhost/:1 Access to fetch at 'http://localhost:8080/something' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
App.js:50 GET http://localhost:8080/something net::ERR_FAILED
App.js:50 method failed
I tried to add "no cors" to fetch but it doesn't change anything. Can anybody tell me how i could fix that?

A trailing slash in cors origin is causing the error.
#CrossOrigin(origins = "http://localhost:3000") // no slash at end in origin.
Hope this fixes your issue.

Related

how do i fix cors error in next js with stripe? [duplicate]

This question already has an answer here:
Stripe Checkout example running into CORS error from localhost
(1 answer)
Closed 3 months ago.
I get a cors error saying `Access to XMLHttpRequest at
'https://checkout.stripe.com/c/pay/cs_test_a13NBIQCPQonxjMN9GGvkS9u71VZGdxxJTZblp8mh8owCu72JIhm3vW3X6#fidkdWxOYHwnPyd1blpxYHZxWjA0T09VamtMZmZhaWx3NGZ3fHMxcXxsc0RxY05GY0QwT2JwNWhEazxsbE83dlNEQGJSdEM1bW9Sc0t8UE11S0B0cUZKfEBsdUwyZDFXTUE3UjZqSzFgbG5oNTVVPVIzaWNWcicpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYHgl' (redirected from 'http://localhost:3000/api/checkout_sessions') 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.`
I tried using rewrites in the next.config.js file but the only problem is that the stripe session id keeps changing.
`
module.exports = {
async rewrites() {
return [
{
source: '/api/checkout_sessions',
destination: 'what do a put here?',
},
]
},
}
`
So far based off my research using next js rewrites is the only way to solve this cors error but if their is any other way, please tell me.
I have a button that sends a post request to /api/checkout_sessions and thats supposed to forward me to a stripe checkout by giving me a session id. But i get a cors error.
There are two ways to solve this problem.
Don’t use XMLHttpRequest or fetch() to redirect to Checkout server-side. Instead, use a normal form submit that triggers a server-side function to create a Checkout Session, so that you can use a 303 redirect on the server-side to redirect to the Session URL
If you still need to use XMLHttpRequest or fetch(), you can return the Session’s URL to the client (in a JSON object, for example). From there you can use client-side code navigates to that URL(for example: via window.location).

react - No 'Access-Control-Allow-Origin' header is present on the requested resource when fetching the images from s3

import imageToBase64 from 'image-to-base64';
...
formatImageToBase64 = () => {
imageToBase64("https://example.s3.ap-southeast-1.amazonaws.com/images/image1") // Path to the image
.then(
(response) => {
console.log(response);
}
)
.catch(
(error) => {
console.log(error);
}
)
}
When I run this function, error occurs as below.
Access to fetch at 'example.s3.ap-southeast-1.amazonaws.com/images/image1?AWSAccessKeyId=qwertyuip12344&Expires=1664366635&Signature=aoqogfjfj3%2Foofofol%3D' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
I checked my S3 setting but it seems no problem.
I also tried to change the AllowedOrigin to '*', but still not working.
Try <AllowedOrigin>*</AllowedOrigin> instead of your localhost and check if it works - if it does then you know the problem is within AllowedOrigin rule.
For more detailed description how to define your CORS just take a look at: S3 - Access-Control-Allow-Origin Header
UPDATE: I've tried to access the link you've provided and what I've got in return is a following message "The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint".
You can follow it up at: AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

CORS error on Axios PUT request from React to Spring API

I am working on an update functionality using PUT. I have a React front end and Spring back-end API. Here is the following PUT request made from front-end:
updateStuff(username, id, stuff){
return Axios.put(`http://localhost:8080/stuff/${username}`, {stuff})
}
Controller to handle this request:
#RestController
#CrossOrigin(origins="http://localhost:3000")
public class StuffController {
#Autowired
private StuffService stuffService;
#PutMapping(path="/stuff/{username}/{id}")
public ResponseEntity<Stuff> updateStuff(#PathVariable String username,
#PathVariable long id,
#RequestBody Stuff stuff) {
Stuff response = stuffService.save(stuff);
return new ResponseEntity<Stuff>(stuff, HttpStatus.OK);
}
I am able to use the same service for GET and DELETE. I am also able to send request using REST client. But when I am trying using browser I am getting this error in console:
Access to XMLHttpRequest at 'http://localhost:8080/stuff/abc' 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.
PUT http://localhost:8080/stuff/abc net::ERR_FAILED
Not able to figure out why its just happening for PUT request? How to resolve this? Appreciate your help and time!
EDIT:
Updated the front-end to:
updateStuff(username, id, stuff){
return Axios.put(`http://localhost:8080/stuff/${username}`, {
headers:{
'Access-Control-Allow-Origin':'*',
'Content-Type': 'application/json;charset=UTF-8',
}
})
}
Still its throwing the same error. So far Spring Security is not configured. I am just checking a simple update flow without any authentication or authorization.
EDIT 2: Request headers in browser has Access-Control-Allow-Origin: *:
I ran into a similar issue a while ago. Check if the variables of your model class in the backend have the same name as in your frontend. That fixed it for me.
The best way to deal with this cors policy is to add a proxy field in the pakage.json file.enter image description here
In reactjs application you can use your spring boot api's URL as proxy to avoid CORS issue.
package.
package.json
{
"proxy": "http://localhost:8080/",
"dependencies": {
.
.
.
}
}
axios
Axios.put(stuff/${username}, {stuff})

Access to XMLHttpRequest blocked by CORS Policy in ReactJS using Axios

I'm setting up stripe connect button in my React Component using Axios. I keep getting this error after redirection
Access to XMLHttpRequest at 'https://connect.stripe.com/oauth/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Thankyou.js:40 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
I get the code from the url and create a curl request using axios.Post. This is the code in my redirect URL
// Thankyou.js
export default class Thankyou extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const code = qs.parse(this.props.location.search, {
ignoreQueryPrefix: true
}).code;
const params = {
client_id: "*******************",
client_secret: "**********************",
grant_type: "authorization_code",
code: code
};
axios
.post(
"https://connect.stripe.com/oauth/token",
// apiBaseUrl,
{ params }
)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
console.log(code);
}
render() {
return (
<div>
<h2>Thank you for connecting with us!</h2>
</div>
);
}
}
There is nothing wrong with your code, but most likely the API endpoint the code trying to reach is not setup for JavaScript web app. CORS policy is set on the server-side and enforced primarily on the browser-side.
The best way to work around is to use Stripe's JavaScript solution such as Strip React Elements or Stripe.js.
A hacky way to get around CORS would be setting up Reverse proxy with solutions such as NGINX. For example, you can use the following nginx configuration:
server {
listen 8080;
server_name _;
location / {
proxy_pass http://your-web-app:2020/;
}
location /stripe/ {
proxy_pass https://connect.stripe.com/;
}
}
By doing so, all the API calls to Stripe.com could be through /stripe under your web app's URL. For example, calling http://yourapp/stripe/oauth/token would be same as calling https://connect.stripe.com/oauth/token
That being said, the second solution is hacky and Stripe may decide to block your reverse proxy server.
basically you need to talk to whoever is hosting this https://connect.stripe.com/oauth/token to enable CORS (Cross Origin Resource Sharing )
It is a security measure implemented by most standard browsers to stop unwanted requests to your backend
It's probably because Stripe doesn't provide JavaScript client so you either have to use your own server proxy or use something like "https://cors-anywhere.herokuapp.com/https://connect.stripe.com/oauth/token"
I hope this answer would be useful to new users:
This issue can be easily fixed by using an annotation in your spring boot rest controller class.
Something like below (also ref screenshot):
#CrossOrigin(origins = "http://localhost:4200")
Explicitly mention the react JS server URL that is causing this issue.
Now after adding above annotation (with your react JS server URL) the browser will allow the flow.
All the best.
Learn about CORS
Think about it, there is anything wrong with your axios.post request, it's successfully contacting the server. But there is one more thing to do before the server let you execute or manipulate it's files.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy.
So your cross-origin request and the server Cross-Origin Resource Sharing (CORS) have to match.
How do you solve it?
Depending on your server and the server side programming language your are implementing, you can configure the different parameters to handle your CORS.
For example, you can configure that the only allowed methods will be:
GET HEAD
So if someone try to axios.post to your server with a different method like POST, it will return an error like this:
Access to XMLHttpRequest at 'https://connect.stripe.com/oauth/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Thankyou.js:40 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
Resources:
https://www.w3.org/TR/cors/
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
I would suggest reading through this site: https://stripe.com/docs/recipes/elements-react
It gives specific instructions straight from stripe on using their API with react. Good luck!

ASP MVC Web api with Angular2 - Http header Access-Control

I have rest application with Angular2 and ASP MVC rest server and I have a problem with communication.
When I send get, I get this error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
When I added Access-Control-Allow-Origin to request, I get this error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.
Here is my code:
let headers = new Headers({ 'Access-Control-Allow-Origin': '*' })
this.http.get("http://localhost/App/Users", { withCredentials: true, headers: headers })
.subscribe(response => {
console.log("A");
}, error => {
console.log(error);
});
In web.config is enabled Windows authentication.
Where is problem?
The problem seems here is of CORS. Your angular and WebAPI are using different ports as you're using localhost. (Seems like they are two different projects).
To solve this you can install the nuget package using "Install-Package Microsoft.AspNet.WebApi.Cors" and then in your WebApiConfig file you can simply say "config.EnableCors()". Now the API which you're exposing to the angular part, has to be told that the CORS is supposed to be used there. So you can put the attribute over your controller mentioning the origin, headers and methods. It should work fine after that.
For more reference, you can check this link,
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
On server side when you enabled cors add:
corsAttr.SupportsCredentials = true;
Like this on MVC .net on Application_Start
var corsAttr = new EnableCorsAttribute("http://localhost:4200,http://domain1,http://domain2", "*", "*");
// Enable withCredentials
corsAttr.SupportsCredentials = true;
config.EnableCors(corsAttr);

Resources