2016-08-12 57 views
1

我在從我的網站鏈接加載字體時出現問題。在我所看到的那裏有一個錯誤,在我的server.js中CORS不存在於我的頭文件中。現在,我的問題是,我將如何將頭插入到我的server.js有人可以幫助我嗎?ReactJS否'訪問控制 - 允許來源'

以下是錯誤的起源「我的網站鏈接」

字體已被跨來源資源共享的政策阻止加載:沒有「訪問控制允許來源」標頭出現在請求的資源。原產地「http://localhost:3001」下面顯示的,因此不允許訪問

const app = express(); 

// 
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the 
// user agent is not known. 
// ----------------------------------------------------------------------------- 
global.navigator = global.navigator || {}; 
global.navigator.userAgent = global.navigator.userAgent || 'all'; 

// 
// Register Node.js middleware 
// ----------------------------------------------------------------------------- 
app.use(express.static(path.join(__dirname, 'public'))); 
app.use(cookieParser()); 
app.use(bodyParser.urlencoded({ extended: true })); 
app.use(bodyParser.json()); 

// 
// Authentication 
// ----------------------------------------------------------------------------- 
app.use(expressJwt({ 
    secret: auth.jwt.secret, 
    credentialsRequired: false, 
    getToken: req => req.cookies.id_token, 
})); 
app.use(passport.initialize()); 

app.get('/login/facebook', 
    passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false }) 
); 
app.get('/login/facebook/return', 
    passport.authenticate('facebook', { failureRedirect: '/login', session: false }), 
    (req, res) => { 
    const expiresIn = 60 * 60 * 24 * 180; // 180 days 
    const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn }); 
    res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true }); 
    res.redirect('/'); 
    } 
); 

// 
// Register API middleware 
// ----------------------------------------------------------------------------- 
app.use('/graphql', expressGraphQL(req => ({ 
    schema, 
    graphiql: true, 
    rootValue: { request: req }, 
    pretty: process.env.NODE_ENV !== 'production', 
}))); 

// 
// Register server-side rendering middleware 
// ----------------------------------------------------------------------------- 
app.get('*', async (req, res, next) => { 
    try { 
    let css = []; 
    let statusCode = 200; 
    const data = { title: '', description: '', style: '', script: assets.main.js, children: '' }; 

    await UniversalRouter.resolve(routes, { 
     path: req.path, 
     query: req.query, 
     context: { 
     insertCss: (...styles) => { 
      styles.forEach(style => css.push(style._getCss())); // eslint-disable-line no-underscore-dangle, max-len 
     }, 
     setTitle: value => (data.title = value), 
     setMeta: (key, value) => (data[key] = value), 
     }, 
     render(component, status = 200) { 
     css = []; 
     statusCode = status; 
     data.children = ReactDOM.renderToString(component); 
     data.style = css.join(''); 
     return true; 
     }, 
    }); 

    const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); 

    res.status(statusCode); 
    res.send(`<!doctype html>${html}`); 
    } catch (err) { 
    next(err); 
    } 
}); 

// 
// Error handling 
// ----------------------------------------------------------------------------- 
const pe = new PrettyError(); 
pe.skipNodeFiles(); 
pe.skipPackage('express'); 

app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars 
    console.log(pe.render(err)); // eslint-disable-line no-console 
    const statusCode = err.status || 500; 
    const html = ReactDOM.renderToStaticMarkup(
    <Html 
     title="Internal Server Error" 
     description={err.message} 
     style={errorPageStyle._getCss()} 
     userAgent={req.headers['user-agent']}> // eslint-disable-line no-underscore-dangle 
     {ReactDOM.renderToString(<ErrorPage error={err} />)} 
    </Html> 
); 
    res.status(statusCode); 
    res.send(`<!doctype html>${html}`); 
}); 

// 
// Launch the server 
// ----------------------------------------------------------------------------- 
/* eslint-disable no-console */ 
models.sync().catch(err => console.error(err.stack)).then(() => { 
    app.listen(port,() => { 
    console.log(`The server is running at http://localhost:${port}/`); 
    }); 
}); 
/* eslint-enable no-console */ 
+0

你有沒有看這份文件,說明如何啓用快遞CORS? http://enable-cors.org/server_expressjs.html – KumarM

+0

@KumarM讓我檢查一下 – dczii

回答

0

您可以插入的標頭。這對我的項目沒有任何問題。

// Where app -> const app = express(); 
app.use(function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
    next(); 
}); 

順便說一句,你可以提高你的代碼app.js分離路由邏輯,並使用路由器:http://expressjs.com/es/api.html#router

希望它幫助。

+0

我已經嘗試添加代碼,但我仍然得到相同的錯誤:( – dczii

+0

@dczii你可以請發表一個要點你的app.js? – Guillermo

+0

@dczii我可能會以一種錯誤的方式表達自己,我需要express.js項目的app.js。 – Guillermo

3

直接從this網站,在快遞啓用CORS:

app.use(function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
    next(); 
}); 

app.get('/', function(req, res, next) { 
    // Handle the get for this route 
}); 

app.post('/', function(req, res, next) { 
// Handle the post for this route 
}); 
+0

對於您的答案,一個很好的改進是使用路由器而不是應用程序。 – Guillermo

+0

@Guillermo感謝您的建議。聽起來不錯。任何可以幫助我瞭解更多信息的鏈接?還是你的意思是像反應路由器? – KumarM

+0

我嘗試添加app.use(函數(req,res,next){res.header(「Access-Control-Allow-Origin」,「*」); res。頭(「Access-Control-Allow-Headers」,「Origin,X-Requested-With,Content-Type,Accept」); next(); }); 但我仍然收到相同的錯誤,並且在加載字體時,標題中仍然沒有訪問控制允許來源 – dczii