即使安装了npm cors
软件包,我也无法访问我的服务器。
import Express from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
/**********************
SERVER CONFIG
*********************/
import serverConfig from './config';
import auth from './routes/v1/auth.routes'
// Initialize Express
const app = new Express();
// DB Setup
mongoose.connect(serverConfig.mongoUrl, error => {
if (error) {
throw new Error('Please make sure Mongodb is installed and running!');
} else {
console.log(`MongoDB is running on port ${serverConfig.mongoUrl}`);
}
});
mongoose.Promise = global.Promise;
/**********************
MIDDLEWARE
*********************/
app.use(cors({
origin: ['http://localhost:8080'],
credentials: true
}));
app.use(compression());
// Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
// This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:
/**********
MULTIPARTY
- It will not create a temp file for you unless you want it to.
- Counts bytes and does math to help you figure out the Content-Length of the final part.
- You can stream uploads to s3 with aws-sdk, for example.
- Less bugs. This code is simpler, has all deprecated functionality removed, has cleaner tests, and does not try to do anything beyond multipart stream parsing.
*********/
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use('/api/v1', auth);
/**********************
START EXPRESS SERVER
*********************/
app.listen(serverConfig.port, () => {
console.log(`Server started on port: ${serverConfig.port}`);
});
路由器文件
import { Router } from 'express';
import * as AuthController from './controllers/auth.controller';
import * as passportConfig from '../../utils/passport.config';
import Passport from 'passport';
// Since we are using tokens, we don't want passport to create a cookie-based session
const requireAuth = Passport.authenticate('jwt', { session: false }); // use after sign in or signed up
const requireSignin = Passport.authenticate('local', { session: false }); // before signin
const router = new Router();
/**********************
AUTHENTICATION
*********************/
// Sign Up New User
// Don't need middleware because signup producers token
router.route('/signup').post(AuthController.signup);
// Sign in Existing User
// Need to provide token after localStrat
router.route('/signin').post(requireSignin, AuthController.signin);
export default router;
答案 0 :(得分:3)
你还应该在cors函数中定义你的原始url,
<template>
<h1>Page 2</h1>
</template>
<script>
export default {
}
</script>
<style scoped>
</style>
希望这有帮助。