I\'m using Reactjs and using API through AJAX in javascript. How can we resolve this issue? Previously I used CORS tools, but now I need to enable CORS.
Possible repeated question from How to overcome the CORS issue in ReactJS
CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross domain.
You can temporary solve this issue by a chrome plugin called CORS.
Use this.
app.use((req,res, next)=>{
res.setHeader('Access-Control-Allow-Origin',"http://localhost:3000");
res.setHeader('Access-Control-Allow-Headers',"*");
res.header('Access-Control-Allow-Credentials', true);
next();
});
It is better to add CORS enabling code on Server Side. To enable CORS in NodeJS and ExpressJs based application following code should be included-
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
if you can not change the server (for example if you use external API), create a proxy server. Please check this post for more details.
I deal with this issue for some hours. Let's consider the request is Reactjs (javascript) and backend (API) is Asp .Net Core.
in the request, you must set in header Content-Type:
Axios({
method: 'post',
headers: { 'Content-Type': 'application/json'},
url: 'https://localhost:44346/Order/Order/GiveOrder',
data: order,
}).then(function (response) {
console.log(response);
});
and in backend (Asp .net core API) u must have some setting:
1. in Startup --> ConfigureServices:
#region Allow-Orgin
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
#endregion
2. in Startup --> Configure before app.UseMvc() :
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
3. in controller before action:
[EnableCors("AllowOrigin")]
Suppose you want to hit https://yourwebsitedomain/app/getNames from http://localhost:3000 then just make the following changes:
packagae.json :
"name": "version-compare-app",
"proxy": "https://yourwebsitedomain/",
....
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
...
In your component use it as follows:
import axios from "axios";
componentDidMount() {
const getNameUrl =
"app/getNames";
axios.get(getChallenge).then(data => {
console.log(data);
});
}
Stop your local server and re run npm start. You should be able to see the data in browser's console logged