如何 运行 django-rest-framework 并在同一个域上做出反应?

How to run django-rest-framework and react on the same domain?

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

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

redux 上使用 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 不能使用相同的端口。当 运行 连接其中一个时,另一个不能 运行 在该端口上。

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

CORS_ORIGIN_ALLOW_ALL = 真

没有两个应用程序可以 运行 在同一台机器的同一端口上。阅读这篇文章的更多内容 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);
});

我喜欢@a_k_v 的回答:setting.py 文件中只有一行。 还有@NAVIN 介绍了一个很棒的 npm 包。 但是对于生产级别,根据人们在 Whosebug 上的讨论,我坚持为 'reactjs-webpack frontend' 和 'django backend' 使用相同的域。这是我的解决方案:我使用 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 的开发模式。