【问题标题】:How to run django-rest-framework and react on the same domain?如何运行 django-rest-framework 并在同一个域上做出反应?
【发布时间】:2018-09-11 17:54:18
【问题描述】:

在使用django-rest-framework 作为后端和reactjs + redux 作为前端的网站上工作。

现在我的后端服务器位于 URL 和端口 http://localhost:8080 上的 vagrant ubuntu 机器上。前端使用 react + redux + webpack(port 80) + cross-fetch 用于 API 请求/响应,服务器在 http://localhost 上。

在使用 cross-fetch 上的 cross-fetch 请求 API 以获取数据时遇到两个错误。

第一个错误:

Failed to load http://localhost/courses-api/all-courses/: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8000' is therefore not allowed access.

是不是因为端口不同?

第二个错误:

Uncaught (in promise) TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (browser-ponyfill.js:445)

找不到解决问题的方法。两者使用相同的端口会解决我的问题吗?在网上找到解决第一个错误的方法,但不能这样做,因为nodejsdjango 不能使用相同的端口。运行其中一个时,另一个无法在该端口上运行。

【问题讨论】:

    标签: node.js redux django-rest-framework fetch redux-thunk


    【解决方案1】:

    我喜欢@a_k_v 的回答:setting.py 文件中只有一行。 @NAVIN 还介绍了一个很棒的 npm 包。 但是对于生产级别,基于人们在 stackoverflow 上的讨论,我坚持为“reactjs-webpack 前端”和“django 后端”使用相同的域。这是我的解决方案:我使用 nginx Web 服务器来处理前端和后端。通过使用 UWSGI 和 django 的套接字以及 webpack 的反向代理,我 终于成功地运行了我的服务器,没有任何错误。

    我的 nginx 配置:

        server{
            listen 80;
            server_name example.com
    
            location /api {
                    include uwsgi_params;
                    uwsgi_pass unix:/home/hamidk1373/uwsgi/pythontraining.sock;
            }
    
            location / {
                    proxy_pass http://127.0.0.1:8000;
                    proxy_set_header Host $host;
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            }
        }
    
    • 我仍处于使用 webpack-dev-server 的开发模式。

    【讨论】:

      【解决方案2】:

      第一个错误是因为跨域资源共享。您需要在服务器中配置 cors。为此,您需要安装 corsheaders 并将其添加到 INSTALLED_APPS 中。然后将其添加到您的 settings.py

      CORS_ORIGIN_ALLOW_ALL = 真

      【讨论】:

      • 谢谢。这是在 localhost 上工作的一个很好的解决方案。它解决了错误。
      【解决方案3】:

      没有两个应用程序可以在同一台机器上的同一端口上运行。阅读这篇文章的更多内容Can two applications listen to the same port?

      对于您的第一个问题,只需在后端使用 cors.js NPM 并使用 express.js 之类的:

      server.js/app.js:

      const CORS            = require('cors'),
            express         = require('express');
      
      const app             = express();
      
      // Cross-Origin Resource Sharing
      app.use(CORS());
      

      对于您的第二个问题:有一个函数返回 promise,但是没有从调用函数中正确处理,或者您的 promise 不是 resolvedrejected

      示例 JS:

      function doSomethingAsync () {
          return new Promise ( (resolve, reject) => {
              // Just to simulate asynchronous functions using setTimeout()
              setTimeout( ()=> {
                  // Doing asynchronous work like File read/write, database calls, API call, any other async.
      
                  // If not resolve/reject function are not called then uncaught in promise error will come. Thus always call these functions.
      
                 if('some condition is true') {
                     resolve('Return success message here');
                 } else {
                     reject('Return your error here');
                 }
              },10000);
          });
      }
      
      doSomethingAsync()
      .then( result => {
          console.log('If promise resolved then here: ', result);
      })
      .catch( err => {
          console.log('If promise rejected then here: ', err);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-15
        • 1970-01-01
        • 2022-01-25
        • 2021-04-02
        相关资源
        最近更新 更多