我知道他们是一个类似this的问题,但它不是专门表达,而是以反应为前端。
我收到此错误。
可以从“ http://localhost:8000/api/users/auth/github”处获取 原产地“ http://localhost:8001”已被CORS政策阻止: 对预检请求的响应未通过访问控制检查: 没有HTTP正常状态。
我的目标是控制台记录响应。
这是我的快速app.js的设置方式
app.js
var express = require('express');
var app = express();
var userRoute = require('./routes/users');
var postRoute = require('./routes/posts');
var bodyParser = require('body-parser');
var logger = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser') ;
var dotenv = require('dotenv');
var env = dotenv.config();
var cors = require('cors');
var models = require('./models/');
const port = process.env.PORT || 8000;
const passport = require('passport');
const path = require('path');
// const allowOrigin = process.env.ALLOW_ORIGIN || '*'
// CORS Middleware
if (!process.env.PORT) {
require('dotenv').config()
}
if (!process.env.PORT) {
console.log('[api][port] 8000 set as default')
console.log('[api][header] Access-Control-Allow-Origin: * set as default')
} else {
console.log('[api][node] Loaded ENV vars from .env file')
console.log(`[api][port] ${process.env.PORT}`)
console.log(`[api][header] Access-Control-Allow-Origin: ${process.env.ALLOW_ORIGIN}`)
}
// app.use(cors({
// origin: process.env.ALLOW_ORIGIN,
// credentials:true,
// allowedHeaders: 'X-Requested-With, Content-Type, Authorization, origin, X-Custom-Header',
// methods: 'GET, POST, PATCH, PUT, POST, DELETE, OPTIONS',
// }));
require('./config/passport-github');
require('./config/passport');
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({
secret : process.env.JWT_SECRET,
saveUninitialized: false,
maxAge: 1000 * 60 * 60 * 84,
resave: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:false}));
const isAuthenticated = function(req, res, next){
if(req.isAuthenticated()){
next();
console.log('this works');
}else{
res.redirect('http://127.0.0.1:8001/signIn');
}
}
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header(' preflightContinue', false)
// res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
// res.header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');
next();
});
app.use('/api/users', userRoute );
app.use('/api/posts', isAuthenticated, postRoute );
app.use(function(req, res, next) {
res.locals.user = req.user; // This is the important line
// req.session.user = user
console.log(res.locals.user);
next();
});
models.sequelize.sync().then(() => {
const server = app.listen(port, () => {
console.log(`Server is up and running on port ${port}`);
});
});
前端
import React, {Component} from 'react';
// import axios from 'axios';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Avatar from '@material-ui/core/Avatar';
import {withStyles} from '@material-ui/core/styles';
import Chip from '@material-ui/core/Chip';
import {connect} from 'react-redux';
import {compose} from 'redux';
import {Redirect} from 'react-router-dom';
import ourStyles from '../styles/ourStyles';
import github from './github/github';
import Axios from '../Axios';
import { history } from '../components/layout/Navbar';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
user: ""
}
}
fetchData = () => { // error happens here
fetch(process.env.REACT_APP_BASE_GITHUB_SIGNIN, {
method: "GET",
headers: {
// 'Access-Control-Allow-Origin':'*',
'Content-Type': 'application/json',
},
})
.then( (res)=> {
console.log(res)
// history.push('/dashboard')
})
.catch( (err) => {
})
}
render() {
const {classes} = this.props;
if (this.props.isAuthenticated) {
return (<Redirect to='/dashboard' />);
}
return (
<div className={classes.root}>
<Grid container justify="center" spacing={44}>
<Grid item sm={7}>
<Paper className={classes.paper}>
<h1>Sign Up</h1>
<Chip
label="Sign In with Github"
clickable
onClick={this.fetchData}
avatar={< Avatar alt = "Natacha" src = "https://avatars0.githubusercontent.com/u/9919?s=280&v=4" />}
// href={process.env.REACT_APP_BASE_GITHUB_SIGNIN}
component="a"
className={classes.chip}/>
<Chip
label="Sign Up with E-Mail"
clickable
href="/signUp"
component="a"
className={classes.chip}/>
</Paper>
</Grid>
</Grid>
</div>
);
}
}
const mapStateToProps = (state) => ({
token: state.user.getToken,
isAuthenticated: state.user.isAuthenticated,
redirectTo: state.user.redirectTo
})
const mapDispatchToProps = (dispatch) => ({
});
// export default withStyles(styles)(Navbar);
export default compose(connect(mapStateToProps, mapDispatchToProps), withStyles(ourStyles))(Home);
其他代码
路由/用户
router.get('/auth/github', passport.authenticate('github') );
router.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/'}),
function(req, res, done) {
console.log(`session ${req.session.passport.user} `); // renders the user id
const user = req.session.passport.user;
if(user){
req.login(user, err => {
const data = {
id: req.session.passport.user
};
models.User.findOne({
where: {
id: data.id,
},
}).then(user => {
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET);
res.cookie("jwt", token, { expires: new Date(Date.now() + 10*1000*60*60*24)});
res.status(200).send({
auth: true,
token: token,
message: 'user found & logged in',
});
})
// res.cookie("jwt", token, { expires: new Date(Date.now() + 10*1000*60*60*24)});
// res.redirect('http://127.0.0.1:8001/dashboard')
});
} else if(user == null) {
console.log(info.message);
res.status(403).send(info.message);
}
});
答案 0 :(得分:1)
将cors
添加到您的后端(在端点上方):
app.use(cors({
'allowedHeaders': ['Content-Type'], // headers that React is sending to the API
'exposedHeaders': ['Content-Type'], // headers that you are sending back to React
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
答案 1 :(得分:0)
app.use(cors());
您已导入cors,但已使用它。
答案 2 :(得分:0)
如果在数据包中收到308响应代码,请尝试在端点的末尾添加或删除“ /”。