由于 CORS,我在從表單創建新用戶時遇到問題。我上周能夠在這個應用程式中使用,但不確定我的服務器(方法、來源、標頭等)或我的 API 呼叫中缺少什么。
以下是控制臺問題部分的建議:
要解決此問題,請在關聯的預檢請求的 Access-Control-Allow-Headers 回應標頭中包含您要使用的其他請求標頭。1 請求請求狀態預檢請求不允許請求標頭 new_user 阻止 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))
我做了一些研究,不確定是否應該制作代理,使用插件等,但我可以使用額外的眼睛。謝謝大家!
uj5u.com熱心網友回復:
如果您已經在使用cors 中間件,則無需手動處理OPTIONS請求,它會為您完成。
洗掉此部分...
// 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();
});
您還應該在路由之前注冊 cors 中間件以及其他中間件。
app.use(cors({
origin: "http://localhost:3000",
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus: 200,
}))
//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);
在客戶端,["*"]是一個無效的請求標頭,需要洗掉。您也沒有正確處理異步回應。它應該是
axios.post("http://localhost:9000/api/new_user", {
userName,
imgUrl,
email,
password,
confirmPassword
}, { withCredentials: true, }).then(res => {
history.push("/dashboard")
console.log(res)
console.log(res.data) // ?? this is where `data` is defined
}).catch(console.error)
uj5u.com熱心網友回復:
我認為這是由這一行引起的,return res.status(200).json({});
當您回應 CORS 飛行前您不應該包含 aContent-Type并且將回傳型別設定為 JSON 時可能正是這樣做的。
嘗試
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET", true);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
return res.status(200).end();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/408023.html
標籤:
