Reputation: 11
I am trying to access express api using ajax and I am not able to solve the CORS error. When I disable it on the browser it works but I want to make it work without it also.
Back end code:-
var express = require('express');
var cors = require('cors')
var app = express();
app.use(cors())
app.get('/', (req, res) => {
console.log("Request incoming...")
let data = [
{
name: "Krish",
age: 23,
hobby: "Football"
},
{
name: "John",
age: 23,
hobby: "Basketball"
}
]
res.send(JSON.parse(JSON.stringify({"data":data})))
});
app.listen(5000, ()=>console.log("Listening on port 5000"))
Front end code:
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<table id="myTable">
<tr>
<th>Name</th>
<th>Age</th>
<th>Hobby</th>
</tr>
</table>
<button id="btn" class="btn btn-primary">Click to get Data</button>
</div>
</div>
<script>
$(document).ready(function(){
$("#btn").on('click', function(){
console.log("Function called")
$.ajax({
url: "http://localhost:5000/",
type: "GET",
crossDomain: true,
//data: JSON.stringify({"data":"Hardik"}),
headers:{ "charset":"UTF-8",
"Accept": "application/json",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Credentials":"true",
"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"
},
dataType: "json",
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function (response) {
console.log(response.data)
},
error: function (xhr, status) {
console.log("Error " + status)
}
});
})
})
</script>
</body>
</html>
Error Message:
Access to XMLHttpRequest at 'http://localhost:5000/' from origin 'null' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains the invalid value 'null//undefined'.
Upvotes: 1
Views: 2294
Reputation: 943571
These are response headers:
"Access-Control-Allow-Origin":"*", "Access-Control-Allow-Credentials":"true", "Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"
It does not make sense to send them from the client to the server.
The server must grant permission to the client. The client cannot grant itself permission.
By adding those headers you turn a simple request into a preflighted one as the browser must ask permission to make a request with custom headers.
The cors module you are using can be configured to allow preflighted requests but in this case you should avoid making the preflight request in the first place.
Remove the custom headers from the client.
Upvotes: 2
Reputation: 91
The CORS error is occurring because of the response from the backend.
As others have mentioned sending those headers in your request does nothing, what you need to do it send those from your backend/api. I see you have some sort of CORS library imported on the backend but evidently it's not working correctly so ensure that it's configured in the right way and installed fully or just paste on the headers you have in your request.
Upvotes: -1