有没有办法解决 cors 政策?
Is there a way on how to solve corse policy?
我正在尝试在我的 mern stack 应用程序中登录,从后面看起来一切正常,前面也是,问题是如果我尝试登录,它说它有 CORS 策略问题.如果我在服务器上添加cors包,服务器不会加载数据。
这是前面部分
constructor(props){
super(props);
this.state = {
userName: '',
password: ''
};
}
handleInputChange = (event) => {
const {value, name} = event.target;
this.setState({
[name]: value
});
};
onSubmit = event => {
event.preventDefault();
fetch('http://localhost:5000/api/users/authenticate', {
method: 'POST',
body: JSON.stringify(this.state),
headers: {
'Content-Type': 'application/json'
}
}).then(res=>{
if (res.status === 200) {
console.log('hello world');
this.props.history.push('/');
}else{
const error = new Error(res.error);
throw error
}
}).catch(err => {
console.error(err);
})
};
这是后面的部分
router.post('/authenticate', (req, res) => {
const { userName, password } = req.body;
if (!userName || !password) {
let msg = "Username or password missing!";
console.error(msg);
res.status(401).json({msg: msg});
return;
}
User.findOne({ userName })
.then(user => {
bcrypt.compare(password, user.password)
.then(isMatch => {
if(!isMatch) return res.status(400).json({ msg: 'Wrong password' });
jwt.sign(
{ id: user.id },
config.get('jwtSecret'),
{ expiresIn: 3600 },
(err, token) => {
if(err) throw err;
res.json({token, user: {
id: user.id,
userName: user.userName
}
});
}
)
})
})
});
基本结果只是能够登录并删除所有与 cors 策略有关的问题。谢谢大家的建议!
很可能您还没有设置服务器来使用 cors
包
const cors = require('cors');
const app = express();
app.use(cors());
在您的 index.js 文件中,
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin:'http://localhost:4200',//development server
optionsSuccessStatus: 200
}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname+ '/client/dist/client'));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname+ '/client/dist/client/index.html'));
});
app.listen(5000, ()=>{
console.log("server is running");
});
很好用const router = express.Router();
您可以简单地:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "*");
next();
});
我正在尝试在我的 mern stack 应用程序中登录,从后面看起来一切正常,前面也是,问题是如果我尝试登录,它说它有 CORS 策略问题.如果我在服务器上添加cors包,服务器不会加载数据。
这是前面部分
constructor(props){
super(props);
this.state = {
userName: '',
password: ''
};
}
handleInputChange = (event) => {
const {value, name} = event.target;
this.setState({
[name]: value
});
};
onSubmit = event => {
event.preventDefault();
fetch('http://localhost:5000/api/users/authenticate', {
method: 'POST',
body: JSON.stringify(this.state),
headers: {
'Content-Type': 'application/json'
}
}).then(res=>{
if (res.status === 200) {
console.log('hello world');
this.props.history.push('/');
}else{
const error = new Error(res.error);
throw error
}
}).catch(err => {
console.error(err);
})
};
这是后面的部分
router.post('/authenticate', (req, res) => {
const { userName, password } = req.body;
if (!userName || !password) {
let msg = "Username or password missing!";
console.error(msg);
res.status(401).json({msg: msg});
return;
}
User.findOne({ userName })
.then(user => {
bcrypt.compare(password, user.password)
.then(isMatch => {
if(!isMatch) return res.status(400).json({ msg: 'Wrong password' });
jwt.sign(
{ id: user.id },
config.get('jwtSecret'),
{ expiresIn: 3600 },
(err, token) => {
if(err) throw err;
res.json({token, user: {
id: user.id,
userName: user.userName
}
});
}
)
})
})
});
基本结果只是能够登录并删除所有与 cors 策略有关的问题。谢谢大家的建议!
很可能您还没有设置服务器来使用 cors
包
const cors = require('cors');
const app = express();
app.use(cors());
在您的 index.js 文件中,
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin:'http://localhost:4200',//development server
optionsSuccessStatus: 200
}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname+ '/client/dist/client'));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname+ '/client/dist/client/index.html'));
});
app.listen(5000, ()=>{
console.log("server is running");
});
很好用const router = express.Router();
您可以简单地:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "*");
next();
});