Reputation: 51
Can you help me, i have a function problematic:
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:
handleSubmit = e => {
e.preventDefault();
const data={
'username' : this.username,
'password' : this.password
}
fetch(process.env.REACT_APP_API_URL+'/api/login', data,{
method:"POST",
headers:{
'accept': 'application/json',
'Access-Control-Allow-Origin': "*",
'content-type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': 'true',
}
})
.then(r => r.json());
}
but there is a problem with the url, how do is solve it? enter image description here
Upvotes: 2
Views: 30078
Reputation: 29
In spring boot you can use annotation "@CrossOrigin". You will pass the url of your react app for parameter origins:
@CrossOrigin(origins = "http://localhost:3000",methods = RequestMethod.GET)
@GetMapping("/courses")
public Iterable<Course> getCourses() {
CourseService courseService=new CourseService();
return courseService.getAllCourses();
}
Upvotes: 3
Reputation: 1183
You can't access resources when the origin
you are accessing to is not the same as the origin
you are using.
As commented by @Freestyle09, you need to enable CORS policies in your backend:
In PHP:
header('Access-Control-Allow-Origin: *');
In node.js (Express):
cors
package from npm.var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
This should set the headers to Access-Control-Allow-Origin: *
, if you want to specify a host:
app.use(cors({
origin: 'http://yourapp.com'
}))
Read more from this answer:
Upvotes: 2
Reputation: 51
Thank you all for your input and answers, this problem has been resolved, and it's running.
this problem is simple, I just add it in pckage.json
"proxy":"http://127.0.0.1:8000",
and i am use in axios fatch
axios({
url:'/api/login',
data:data,
method:"POST",
mode: 'no-cors',
headers:{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": process.env.REACT_APP_API_URL,
"Access-Control-Request-Headers": 'Content-Type, Authorization'
}
})
.then(res => {
console.log(res);
})
.catch(err =>{
console.log(err);
})
and it's work for me thank you all (n_n)
Upvotes: 2