Reputation: 1460
Hi I've been scrambling the web for hours now trying to find a solution.
I'm trying to make a post request to my own web server hosted by Namecheap.
Here's my Ajax code to call the Post request. Note: I can't show the url sorry.
$.ajax({
url: "https://api.someurl.com/something" + avariable + "/" + anotherthing,
type: "POST",
crossDomain: true,
dataType: "json",
success: function (response) {
var resp = JSON.parse(response)
console.log(resp)
},
error: function (xhr, status) {
console.log("error")
}
});
This was a code i got from another stackoverflow post's answer which had the most upvotes. It didn't seem to work. actually all of them didn't work.
I'm calling this ajax from a index.html I have running on my localhost.
And i got this error:
Access to XMLHttpRequest at 'the url i cant show' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Any help would be much appericiated! I've never encountered this issue before and I don't know how to handle it.
Update 1 I have access to the backend server. Its running Flask on Python.
Any ideas how I can enable the CORS thing there?
Also I'm not sure what the origin of this index.html will be. Because I'll be packaging it into an electron js
desktop application.
Upvotes: 1
Views: 763
Reputation: 2904
Install flask-cors
in your flask app:
pip install -U flask-cors
Then in your code:
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
@app.route("/something+avariable/anotherthing")
@cross_origin()
def yourfunction():
Alternatively, add it manually:
def after_request(response):
header = response.headers
header['Access-Control-Allow-Origin'] = '*'
return response
If you need it for development only then you can use a CORS browser extension such as this for Chrome and this for FireFox.
Upvotes: 1
Reputation: 1
CORS stands for Cross Origin Resource Sharing.
Its just a mechanism to block unauthorized request to a server.
On your backend you will have yo authorize the address you are using to access your backend.
For php:
Upvotes: 0