Can't get response from API

I am sending a value into erpnext from another server using jquery ajax(). I have send the value into erpnext and print it in terminal, It’s working. But when I try to return some value then an error occured, the error is “Access to XMLHttpRequest at ‘http://192.168.0.108:8000/api/method/my_appname.api.my_function?my_data=Testing%20form%20ajax’ from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

Javascript code is:
$(document).ready(function(){
$.ajax({
crossOrigin: true,
url: “http://192.168.0.108:8000/api/method/my_appname.api.my_functionname”,
method: “GET”,
async: false,
crossDomain: true,
data: {my_data:“Testing form ajax”},
success: function(data) {
console.log(data);
}
});
});
Python code:
def get_from_data(my_data):
print (my_data)
return “test”

Maybe this will help you: Implement HTTP OPTIONS to support CORS access management · Issue #5868 · frappe/frappe · GitHub

By the way, I would appreciate nicely formatted code next time. :wink: If one can read it easily you are more likely to get help. Example:

def get_from_data(my_data):
    print (my_data)
    return "test"

I already set up nginx (use the command bench setup nginx). And copy, paste this comment into the nginx.conf
**
if ($request_method = OPTIONS ) {
Preformatted textadd_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
**
But the error shown still now.

Did you try this nginx.conf

Yes I did it. But the error was same.
I use this command sudo nginx -t
Output is
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

And run sudo service nginx restart this command
output is
**Job for nginx.service failed because the control process exited with error code. See “systemctl status nginx.service” and “journalctl -xe” for details.
**

Chrome is extremely aggressive about CORS. Even if the target server changes it’s configuration Chrome still won’t touch it. It’s as if it puts a lifetime ban on that host.

When trying to solve CORS problems always use a different browser to double check that the host configuration really is to blame.

1 Like

Problem solved.
When I run the command bench setup nginx , one file created nginx.conf into the frappe-bench/config/ folder. And in this file my site assign with the port number 8003.
But my localhost running into port number 8000.
Initially I was trying to send the request on port number 8000, later on I change the port number to 8003 and it works.