用 koa 和 nodejs 创建了一个 api 接口,开启了跨域,大概代码如下
入口文件 app.js
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors');
require('dotenv').config();
const authRoutes = require('./api/routes/auth');
const app = new Koa();
app.use(cors({
origin: '*',
allowMethods: ['POST'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept']
}));
app.use(bodyParser());
app.use(authRoutes.routes());
app.listen(process.env.PORT || 3001, () => {
console.log('Server started');
});
路由文件 routes/auth.js 的代码如下
const Router = require('koa-router');
const authController = require('../controllers/auth');
const router = new Router();
router.post('/register', authController.register);
router.post('/login', authController.login);
router.post('/forgotpassword', authController.forgotPassword);
router.post('/resetpassword', authController.resetPassword);
router.post('/updateprofile', authController.updateProfile);
module.exports = router;
控制器 controllers/auth.js 的部分代码如下
// 一些 const
exports.register = async (ctx) => {
const { username, password, email } = ctx.request.body;
const emailRegex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
if (!username || !password || !email || !emailRegex.test(email)) {
ctx.throw(400, 'Invalid username, password, or email');
}
// 略
};
exports.login = async (ctx) => {
const { email, password } = ctx.request.body;
const emailRegex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
if (!email || !password || !emailRegex.test(email)) {
ctx.throw(400, 'Invalid email or password');
}
// 略
};
exports.forgotPassword = async (ctx) => {
const { email } = ctx.request.body;
const emailRegex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
if (!email || !emailRegex.test(email)) {
ctx.throw(400, 'Invalid email');
}
// 略
};
exports.resetPassword = async (ctx) => {
const { password, resetToken } = ctx.request.body;
// 略
};
exports.updateProfile = async (ctx) => {
// 略
};
我现在遇到的问题是,该接口程序是部署在本地电脑 3001 接口,即 http://localhost:3001
- 如果在本地电脑直接用调试工具调试这几个接口,或者用 curl,都能正常访问
- 但如果在本地用其它程序调用,比如用运行在 http://localhost:3000/ 的页面,这几个接口只有 forgotpassword 一切正常,其它的接口访问时都出现错误,错误信息是跨域,错误信息如下
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401.
请问这个错误在哪里?