【发布时间】:2022-01-10 22:59:07
【问题描述】:
由于 CORS,我在从表单创建新用户时遇到问题。我上周可以在这个应用程序中使用,但不确定我的服务器(方法、来源、标头等)或我的 API 调用中缺少什么。
以下是控制台问题部分的建议:
要解决此问题,请在关联的预检请求的 Access-Control-Allow-Headers 响应标头中包含您要使用的其他请求标头。 1 个请求 请求状态 Preflight Request Disallowed 请求标头 新用户被阻止 new_user 内容类型
这是服务器代码:
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
// Cookies:
const cookieParser = require('cookie-parser');
require('./config/mongoose.config');
app.use(cookieParser());
//required for post request
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// routes:
require('./routes/user.routes')(app);
require('./routes/spot.routes')(app);
// blocking cors errors:
const corsOptions = {
origin: 'http://localhost:3000',
methods: ["GET", "POST"],
allowedHeaders: ["*"],
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus: 200,
}
app.use(cors(corsOptions)) // Use this after the variable declaration
// MIDDLEWARE:
// app.use(cors(
// { credentials: true, origin: 'http://localhost:3000' },
// { headers: { "Access-Control-Allow-Origin": "*" } }));
// Middleware CORS API CALLS:
app.use((req, res, next) => {
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET", true);
return res.status(200).json({});
}
next();
});
//listen on port:
app.listen(9000, () => {
console.log("Listening at Port 9000")
})
路线如下:
const UserController = require('../controllers/user.controllers');
const { authenticate } = require('../config/jwt.config');
module.exports = function (app) {
app.post('/api/new_user', authenticate, UserController.register);
app.get('/api/users', UserController.getAllUsers);
app.get('/api/users/:id', UserController.login);
app.post('/api/users/logout', UserController.logout);
app.put('/api/users/:id', UserController.updateUser);
app.delete('/api/users/:id', UserController.deleteUser);
}
这里是客户端(表单代码):
const onSubmitHandler = e => {
e.preventDefault();
const { data } =
axios.post('http://localhost:9000/api/new_user', {
userName,
imgUrl,
email,
password,
confirmPassword
},
{ withCredentials: true, },
// { headers: { 'Access-Control-Allow-Origin': '*' } }
{ headers: ["*"] }
)
.then(res => {
history.push("/dashboard")
console.log(res)
console.log(data)
})
.catch(err => console.log(err))
我做了一些研究,不确定是否应该制作代理、使用插件等,但我可以使用额外的眼睛。谢谢大家!
【问题讨论】:
标签: javascript express axios cors