我试图将请求发送到服务器,但被“ CORS策略阻止”,使ngrok在backgrond上运行,并且将其链接用作axios中的baseUrl,我使用了app.use(cors()), “ proxy”:“ link”位于前端,我也曾尝试在其中进行过http-proxy-middleware的操作,但仍然遇到CORS的麻烦
http-proxy
----------
app.use(
proxy('/auth/google', {target: 'http://localhost:2000', changeOrigin: true})
);
app.use(
proxy('/api/**', {target: 'http://localhost:2000', changeOrigin: true})
);
Express
--------
require('dotenv').config();
require('./server/models/Query');
require('./server/models/User');
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const keys = require('./server/config/keys');
const authRoutes = require('./server/routes/authRoutes');
const queryRoutes = require('./server/routes/queryRoutes');
const feedRoutes = require('./server/routes/feedRoutes');
const app = express();
app.use(bodyParser.json());
app.use(authRoutes);
app.use(queryRoutes);
app.use(feedRoutes);
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
});
app.use(cors());
const PORT = process.env.PORT || 2000;
app.listen(PORT);
authRoute
---------
router.post('/signup', async (req, res) => {
const {email, password, type, fName, lName, city} = req.body;
console.log('body from signup', res.body);
try {
const user = new User({
type,
fName,
lName,
city,
email,
});
await user.save();
const token = jwt.sign({userId: user._id}, process.env.COOKIE_KEY);
console.log(token);
res.send({token});
} catch (err) {
return res.status(422).send(err.message);
}
});
答案 0 :(得分:-1)
在快递服务器中有多种处理cors的方法。试试这个。我在每个节点快速服务器中都使用此代码段来解决问题。
//Cross Origin Handle Middleware
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
if( req.method === 'OPTIONS'){
req.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
猫鼬连接后,您必须使用此中间件。无需为此使用cors库。如果您要使用这种中间件方法。我认为这会有所帮助。 :)
答案 1 :(得分:-1)
在任何路线之前,我都应该将cors()移走