Nginx and Django Rest Api CallBest Practices for securing a REST API / web serviceCalling an external command in PythonBest practices for API versioning?PUT vs. POST in RESTWhat exactly is RESTful programming?Does Django scale?Node.js + Nginx - What now?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?SOAP vs REST (differences)No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

What should be the ideal length of sentences in a blog post for ease of reading?

How to test the sharpness of a knife?

Why is the sun approximated as a black body at ~ 5800 K?

Given this phrasing in the lease, when should I pay my rent?

What in this world is she trying to say?

I'm just a whisper. Who am I?

Air travel with refrigerated insulin

Personal or impersonal in a technical resume

Make a Bowl of Alphabet Soup

Sigmoid with a slope but no asymptotes?

Overlapping circles covering polygon

How to I force windows to use a specific version of SQLCMD?

What is the meaning of "You've never met a graph you didn't like?"

Unable to disable Microsoft Store in domain environment

Quoting Keynes in a lecture

Possible Eco thriller, man invents a device to remove rain from glass

Ways of geometrical multiplication

Review your own paper in Mathematics

If Captain Marvel (MCU) were to have a child with a human male, would the child be human or Kree?

Should I warn a new PhD Student?

When and why was runway 07/25 at Kai Tak removed?

Why is the principal energy of an electron lower for excited electrons in a higher energy state?

Check if object is null and return null

Would this string work as string?



Nginx and Django Rest Api Call


Best Practices for securing a REST API / web serviceCalling an external command in PythonBest practices for API versioning?PUT vs. POST in RESTWhat exactly is RESTful programming?Does Django scale?Node.js + Nginx - What now?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?SOAP vs REST (differences)No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API













0















I'm currently developing a web NER application with following stack:



  1. Ubuntu 18.04.1 x64

  2. nginx version: nginx/1.14.0 (Ubuntu)

  3. Django 1.11.20

(I just followed this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04)



My goal is to create a REST API endpoint. Because I do not use any Django model, ive decided not to use Django rest api framework. I have created a simple view handler function:



@csrf_exempt
def test(request):
data = json.loads(request.body.decode('utf8'))

#do some tensorflow stuff here, and return predictions

data['res'] = "String that might contain unicode chars, e.g č,š or others"
return JsonResponse(data, safe=False)


And I a call function from FE:



var url = baseURL + "/ner/api/predict"
var xmlhttp = new XMLHttpRequest();
var data =
"sentence" : "String that might contain unicode chars, e.g č,š or others"

xmlhttp.onreadystatechange = function()
if (this.readyState == 4 && this.status == 200)
var response = JSON.parse(this.responseText);
console.log(response )

;
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-type', 'application/json')
xmlhttp.send(JSON.stringify(data));


This works well in my local dev. environment (win10 + django). Problem arises when I push this codebase to server, CORS seems to be a problem.



ner.js:83 OPTIONS <url here>/ner/api/predict 500 (Internal Server Error)
<url here>/:1 Access to XMLHttpRequest at '<url here>/ner/api/predict' from origin '<url here>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.


So I tried to edit my nginx configuration but I cant solved this.



 location / 
add_header Access-Control-Allow-Origin '*' always;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header Access-Control-Allow-Headers 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Sin$
add_header Access-Control-Max-Age 1728000 always;
include proxy_params;
proxy_connect_timeout 100s;
proxy_send_timeout 100s;
proxy_read_timeout 100s;
proxy_pass http://unix:/home/<path>.sock;



Is there a way how to fix this issue?
Thank you










share|improve this question



















  • 1





    What's the problem?

    – Henry Woody
    Mar 7 at 21:50











  • Sorry I have posted half of question by mistake ")

    – Jerry Smith
    Mar 7 at 22:08











  • The request is causing a 500 internal failure in the server. Check your server logs to see what messages (if any) the server logs before it sends that 500 response.

    – sideshowbarker
    Mar 12 at 11:45















0















I'm currently developing a web NER application with following stack:



  1. Ubuntu 18.04.1 x64

  2. nginx version: nginx/1.14.0 (Ubuntu)

  3. Django 1.11.20

(I just followed this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04)



My goal is to create a REST API endpoint. Because I do not use any Django model, ive decided not to use Django rest api framework. I have created a simple view handler function:



@csrf_exempt
def test(request):
data = json.loads(request.body.decode('utf8'))

#do some tensorflow stuff here, and return predictions

data['res'] = "String that might contain unicode chars, e.g č,š or others"
return JsonResponse(data, safe=False)


And I a call function from FE:



var url = baseURL + "/ner/api/predict"
var xmlhttp = new XMLHttpRequest();
var data =
"sentence" : "String that might contain unicode chars, e.g č,š or others"

xmlhttp.onreadystatechange = function()
if (this.readyState == 4 && this.status == 200)
var response = JSON.parse(this.responseText);
console.log(response )

;
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-type', 'application/json')
xmlhttp.send(JSON.stringify(data));


This works well in my local dev. environment (win10 + django). Problem arises when I push this codebase to server, CORS seems to be a problem.



ner.js:83 OPTIONS <url here>/ner/api/predict 500 (Internal Server Error)
<url here>/:1 Access to XMLHttpRequest at '<url here>/ner/api/predict' from origin '<url here>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.


So I tried to edit my nginx configuration but I cant solved this.



 location / 
add_header Access-Control-Allow-Origin '*' always;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header Access-Control-Allow-Headers 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Sin$
add_header Access-Control-Max-Age 1728000 always;
include proxy_params;
proxy_connect_timeout 100s;
proxy_send_timeout 100s;
proxy_read_timeout 100s;
proxy_pass http://unix:/home/<path>.sock;



Is there a way how to fix this issue?
Thank you










share|improve this question



















  • 1





    What's the problem?

    – Henry Woody
    Mar 7 at 21:50











  • Sorry I have posted half of question by mistake ")

    – Jerry Smith
    Mar 7 at 22:08











  • The request is causing a 500 internal failure in the server. Check your server logs to see what messages (if any) the server logs before it sends that 500 response.

    – sideshowbarker
    Mar 12 at 11:45













0












0








0








I'm currently developing a web NER application with following stack:



  1. Ubuntu 18.04.1 x64

  2. nginx version: nginx/1.14.0 (Ubuntu)

  3. Django 1.11.20

(I just followed this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04)



My goal is to create a REST API endpoint. Because I do not use any Django model, ive decided not to use Django rest api framework. I have created a simple view handler function:



@csrf_exempt
def test(request):
data = json.loads(request.body.decode('utf8'))

#do some tensorflow stuff here, and return predictions

data['res'] = "String that might contain unicode chars, e.g č,š or others"
return JsonResponse(data, safe=False)


And I a call function from FE:



var url = baseURL + "/ner/api/predict"
var xmlhttp = new XMLHttpRequest();
var data =
"sentence" : "String that might contain unicode chars, e.g č,š or others"

xmlhttp.onreadystatechange = function()
if (this.readyState == 4 && this.status == 200)
var response = JSON.parse(this.responseText);
console.log(response )

;
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-type', 'application/json')
xmlhttp.send(JSON.stringify(data));


This works well in my local dev. environment (win10 + django). Problem arises when I push this codebase to server, CORS seems to be a problem.



ner.js:83 OPTIONS <url here>/ner/api/predict 500 (Internal Server Error)
<url here>/:1 Access to XMLHttpRequest at '<url here>/ner/api/predict' from origin '<url here>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.


So I tried to edit my nginx configuration but I cant solved this.



 location / 
add_header Access-Control-Allow-Origin '*' always;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header Access-Control-Allow-Headers 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Sin$
add_header Access-Control-Max-Age 1728000 always;
include proxy_params;
proxy_connect_timeout 100s;
proxy_send_timeout 100s;
proxy_read_timeout 100s;
proxy_pass http://unix:/home/<path>.sock;



Is there a way how to fix this issue?
Thank you










share|improve this question
















I'm currently developing a web NER application with following stack:



  1. Ubuntu 18.04.1 x64

  2. nginx version: nginx/1.14.0 (Ubuntu)

  3. Django 1.11.20

(I just followed this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04)



My goal is to create a REST API endpoint. Because I do not use any Django model, ive decided not to use Django rest api framework. I have created a simple view handler function:



@csrf_exempt
def test(request):
data = json.loads(request.body.decode('utf8'))

#do some tensorflow stuff here, and return predictions

data['res'] = "String that might contain unicode chars, e.g č,š or others"
return JsonResponse(data, safe=False)


And I a call function from FE:



var url = baseURL + "/ner/api/predict"
var xmlhttp = new XMLHttpRequest();
var data =
"sentence" : "String that might contain unicode chars, e.g č,š or others"

xmlhttp.onreadystatechange = function()
if (this.readyState == 4 && this.status == 200)
var response = JSON.parse(this.responseText);
console.log(response )

;
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-type', 'application/json')
xmlhttp.send(JSON.stringify(data));


This works well in my local dev. environment (win10 + django). Problem arises when I push this codebase to server, CORS seems to be a problem.



ner.js:83 OPTIONS <url here>/ner/api/predict 500 (Internal Server Error)
<url here>/:1 Access to XMLHttpRequest at '<url here>/ner/api/predict' from origin '<url here>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.


So I tried to edit my nginx configuration but I cant solved this.



 location / 
add_header Access-Control-Allow-Origin '*' always;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header Access-Control-Allow-Headers 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Sin$
add_header Access-Control-Max-Age 1728000 always;
include proxy_params;
proxy_connect_timeout 100s;
proxy_send_timeout 100s;
proxy_read_timeout 100s;
proxy_pass http://unix:/home/<path>.sock;



Is there a way how to fix this issue?
Thank you







python django rest nginx cors






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 22:07







Jerry Smith

















asked Mar 7 at 21:48









Jerry SmithJerry Smith

295




295







  • 1





    What's the problem?

    – Henry Woody
    Mar 7 at 21:50











  • Sorry I have posted half of question by mistake ")

    – Jerry Smith
    Mar 7 at 22:08











  • The request is causing a 500 internal failure in the server. Check your server logs to see what messages (if any) the server logs before it sends that 500 response.

    – sideshowbarker
    Mar 12 at 11:45












  • 1





    What's the problem?

    – Henry Woody
    Mar 7 at 21:50











  • Sorry I have posted half of question by mistake ")

    – Jerry Smith
    Mar 7 at 22:08











  • The request is causing a 500 internal failure in the server. Check your server logs to see what messages (if any) the server logs before it sends that 500 response.

    – sideshowbarker
    Mar 12 at 11:45







1




1





What's the problem?

– Henry Woody
Mar 7 at 21:50





What's the problem?

– Henry Woody
Mar 7 at 21:50













Sorry I have posted half of question by mistake ")

– Jerry Smith
Mar 7 at 22:08





Sorry I have posted half of question by mistake ")

– Jerry Smith
Mar 7 at 22:08













The request is causing a 500 internal failure in the server. Check your server logs to see what messages (if any) the server logs before it sends that 500 response.

– sideshowbarker
Mar 12 at 11:45





The request is causing a 500 internal failure in the server. Check your server logs to see what messages (if any) the server logs before it sends that 500 response.

– sideshowbarker
Mar 12 at 11:45












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55053335%2fnginx-and-django-rest-api-call%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55053335%2fnginx-and-django-rest-api-call%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page