I've searched for answers to this issue for nearly two weeks. I have a simple system built in web2py. Note: I'm not exactly a python veteran. I am attempting to use the web2py rest api to post data to the database. If I run the curl command, the database table is updated and the rest returns the id of the newly added row. This is the desired outcome. However, if I attempt to use an ajax request to perform the same action, the request runs successful but the rest returns an empty object and the database is not updated. I've added a CORS wrapper class which allows me to get past the cross-origin issue; but I'm not sure if this is at the same time preventing the database from updating etc. I'm stomped. Also note that I formatted the data (in the ajax call) as a json object as well, but still nothing. Please find all the code below.
MOST IMPORTANT: I am receiving the following message - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Any/All help is greatly appreciated guys. Thanks :)
#Web2py model
db.define_table(‘myboard',
#Field('userid','reference auth_user'),
Field('userid',db.auth_user,default=auth.user_id),
Field('title',requires=IS_LENGTH(100,1),label=“Board Title"),
Field(‘idea_a',requires=IS_LENGTH(75,1),label=“Idea A"),
Field(‘idea_b',requires=IS_LENGTH(75,1),label=“Idea B"),
Field('description','text',requires=IS_LENGTH(250,1),label=“Board Description"),
Field('contributors','integer',default='0'),
Field('status','integer',writable=False,readable=False,default='1'), #1=draft, 2=public
Field('created_on','datetime',writable=False,default=request.now))
#Web2py controllers
def CORS(f):
"""
Enables CORS for any action
"""
def wrapper(*args, **kwargs): #*args, **kwargs
if request.env.http_origin:
response.headers['Access-Control-Allow-Origin'] = request.env.http_origin
response.headers['Access-Control-Allow-Credentials'] = "true";
response.headers['Access-Control-Allow-Headers'] = "Authorization,Content-Type,data";
return dict()
return f(*args, **kwargs)
return wrapper
auth.settings.allow_basic_login = True
@CORS
@request.restful()
def api():
from gluon.serializers import json
response.view = 'generic.'+request.extension
def GET(*args,**vars):
patterns = 'auto'
parser = db.parse_as_rest(patterns,args,vars)
if parser.status == 200:
return dict(content=parser.response)
else:
raise HTTP(parser.status,parser.error)
def POST(table_name,**vars):
return json(db[table_name].validate_and_insert(**vars))
return dict()
def PUT(table_name,record_id,**vars):
return db(db[table_name]._id==record_id).update(**vars)
def DELETE(table_name,record_id):
return db(db[table_name]._id==record_id).delete()
return dict(GET=GET, PUT=PUT, POST=POST, DELETE=DELETE)
//CURL COMMAND - This Works!
curl -i --user somename@gmail.com:thepassword -H Accept:application/json -X POST http://127.0.0.1:8000/cc/default/api/myboard.json -H Content-Type: application/json -d 'userid=2&title=THE_TITLE&description=THE_DESCRIP&idea_a=THE 1st idea&idea_b=THE 2nd idea’
//AJAX CALL - Doesn't Work :(
var userid = 2;
var title = "THE_TITLE_HERE";
var description = "THE_DESCRIPTION_HERE"
var idea_a = "THE 1st idea";
var idea_b = "THE 2nd idea";
var userID = ’somename@gmail.com';
var password = ’thepassword';
var theData = "userid=2&title="+title+"&description="+description+”&idea_a=“+ideaA+”&idea_b=“+ideaB;
$.ajax({
type: 'POST',
headers: {"Authorization": "Basic " + btoa(userID + ":" + password)},
url: "http://127.0.0.1:8000/cc/default/api/myboard.json",
contentType: "application/json; charset=utf-8",
data: theData,
success: function (data,textStatus,jqXHR) {
alert(textStatus);
console.log(data);
},
error: function(){
alert("Cannot get data");
}
});
The database table does not update but the request runs successfully. It returns an empty object each time.. {}