2017-07-27 43 views
0

所以我一直在研究一個將請求發送到Django REST-API的React項目。問題是,我似乎無法解決CORS的問題。前端完全與後端隔離。爲了確保網站正常工作,我需要讓Django爲前端文件提供服務。我不知道從哪裏開始,我如何設置Django + React環境,因此我不必處理CORS問題?如何設置Django和React項目而無需處理CORS?

+3

你不能「不必處理CORS問題」。這是一個瀏覽器安全。你必須處理它。你真正的問題是什麼?你的API是否在另一個域上,而不是你所服務的HTML頁面? –

+2

另外,你看過嗎? http://www.django-rest-framework.org/topics/ajax-csrf-cors/#cors –

+0

來自Antoine Pinsard鏈接的文檔:_「在REST框架中處理CORS的最佳方式是添加所需的響應這確保CORS被透明地支持,而不必改變視圖中的任何行爲。「_ –

回答

0

我處理它的方式(也用在DJANGO中編寫的後端)是我的反應應用程序使用NodeJs進行服務器端呈現和轉發api請求。這使我可以將節點服務器上的請求轉發給django服務器。

去看一下一本的NodeJS - 快遞服務實現:

import path from 'path' 
import express from 'express' 
import compression from 'compression' 
import React from 'react' 
import { renderToString } from 'react-dom/server' 
import { match, RouterContext } from 'react-router' 
import configureStore from 'data/redux/store'; 
import proxy from 'http-proxy-middleware'; 
import { Provider } from 'react-redux'; 
import { IntlProvider } from 'react-intl'; 
import routes from './routes'; 

const store = configureStore(); 
const app = express(); 
app.use(compression()); 

//template engine 
app.set('view engine', 'ejs'); 
//where to look for templates 
app.set('views', path.join(__dirname, '/public')); 
//Serve static files 
app.use(express.static(path.join(__dirname, '/public'), { index: false })); 

//middleware for handling api request 
app.use('/api/*', proxy({ 
    target: process.env.API_HOST, 
    pathRewrite: { '^/api/': '' }, 
    changeOrigin: true, 
    secure: false, 
})); 

app.use('/media/*', proxy({ 
    target: process.env.API_HOST, 
    changeOrigin: true, 
    secure: false, 
})); 

app.get('*', (req, res) => { 
    match({ routes: routes(store), location: req.url }, (err, redirect, props) => { 
     if (err) { 
      res.status(500).send(err.message) 
     } else if (redirect) { 
      res.redirect(redirect.pathname + redirect.search) 
     } else if (props) { 
      const appHtml = renderToString(
       <Provider store={store}> 
        <IntlProvider locale="en"> 
         <RouterContext store={store} {...props} /> 
        </IntlProvider> 
       </Provider> 
      ); 
      res.render('index', { appHtml }); 
     } else { 
      res.status(404).send('Not Found') 
     } 
    }) 
}); 

const PORT = process.env.PORT || 8080; 
app.listen(PORT, function() { 
    console.log('Production Express server running at localhost:' + PORT) 
}); 

所以我的NodeJS服務器,服務器反應的應用程序,並通過轉發他們的Django服務器和返回迴響應客戶端處理開始/api/傳入的請求。

+0

你有一個完整的示例源代碼描繪上述流程? –

+0

我不幸。但上面的例子就是這樣。甚至webpack-dev-server也提供了這個功能。 https://webpack.js.org/configuration/dev-server/#devserver-proxy – Tomasz

0

我可以通過將django與反應鬆散耦合來做到這一點。像這樣工作:我在應用程序內的一個文件夾中啓動了一個新的帶有webpack的npm項目,我需要響應前端(my_app/react_frontend)。所以我建立了我的反應前端在這個文件夾,其中有一個index.html(公衆之一)裏面。此index.html成爲我在主url(render(index.html))的views.py中創建的一個索引視圖的模板文件。接下來你需要一個django的中間件來處理webpack。我在這裏使用這個小型圖書館:https://github.com/ezhome/django-webpack-loader。您必須在settings.py和webpack.config.js中仔細配置這些文件夾,例如在模板設置中包含react_frontend文件夾。

最後我運行我的webpack dev-server與watch模式以及django dev server一起開發。這是,我在packages.json中的啓動腳本是"start": "./node_modules/.bin/webpack --config webpack.config.js --watch"

這樣,我的反應前端僅在index.html上與django耦合。所有對後端的ajax調用都直接指向DRF視圖。我不需要這樣處理CORS問題。 CSFR問題很簡單,因爲我只需將{%csrf_token%}放在index.html文件中。 我希望這可以幫助。

相關問題