2016-08-12 1 views
1

내 웹 사이트의 링크에서 내 글꼴을로드하는 데 문제가 있습니다. 내가 본 것 중에 CORS가 내 머리글에없는 내 server.js에 오류가 있습니다. 이제, 제 문제는 헤더를 내 server.js에 어떻게 삽입합니까 누군가 나를 도울 수 있습니까? 여기 ReactJS No 'Access-Control-Allow-Origin'

은 '내 웹 사이트 링크'원점에서

글꼴 간 리소스 공유 정책에 의해 차단 되었기 때문에로드 오류입니다 : 없음 '액세스 제어 - 허용 - 원산지'헤더가에 존재 요청한 자원. 아래 켰을 때, 기원 '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

당신은 삽입 할 수 있습니다 헤더를 사용할 수 없습니다. 이것은 아무런 문제없이 내 프로젝트에서 일하고있다. 그것이 도움이 http://expressjs.com/es/api.html#router

희망 : 그런데

// 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에서 라우팅 로직을 분리하고, 라우터를 사용하여 코드를 향상시킬 수 있습니다. 표현에 CORS를 활성화하는 방법에 대한 직선 this 웹 사이트에서

+0

코드 추가를 시도했지만 여전히 같은 오류가 발생합니다. ( – dczii

+0

@dczii app.js? – Guillermo

+0

@dczii 잘못된 방식으로 표현 될 수도 있습니다. express.js 프로젝트의 app.js가 필요합니다. – Guillermo

3

는 :

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 (function (req, res, next)) { res.header ("Access-Control-Allow-Origin", "*"); res를 추가하려고 시도했다.헤더 ("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }}); 하지만 여전히 동일한 오류가 발생하고 글꼴을로드 할 때 여전히 액세스 제어가 없습니다. 머리글에 출처가 허용됩니다. – dczii