API axios 始终未定义请求 POST
API req always undefined from axios POST
我使用了中间件,但仍然无法从请求中得到 undefined。我在客户端使用 axios POST 方法。这是我的代码。
app.ts:
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import userAuth from './routes/userAuth';
const app = express();
dotenv.config();
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use(express.json());
app.use(cors());
app.use('/userAuth', userAuth);
const CONNECTION_URL = process.env.MONGO_CONNECTION_URL!;
const PORT = process.env.PORT || 4000;
mongoose
.connect(CONNECTION_URL)
.then(() => {
app.listen(PORT, () =>
console.log(`Server is running on port ${PORT}`),
);
})
.catch((error) => {
console.log(error);
});
./route/userAuth.ts:
import { Router } from 'express';
import { register } from '../controllers/userAuth';
const router = Router();
router.post('/register', register);
export default router;
../controllers/userAuth:
import mongoose from 'mongoose';
import { Router as router, ErrorRequestHandler } from 'express';
import UserAuth from '../models/userAuthScema';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
export const register: ErrorRequestHandler = async ({ req, res }) => {
console.log(req);
if (!req) {
res.json({ message: `Req Undefined.` });
return;
}
let { userType, email, fName, lName, confirmPassword } = req.body;
let { password } = req.body;
const takenEmail = await UserAuth.findOne({ email });
const passwordValidationFailed = password !== confirmPassword;
if (takenEmail) res.json({ message: `User email has already been used.` });
else if (passwordValidationFailed)
res.json({ message: `Fail password validation.` });
else {
password = await bcrypt.hash(password, 10);
const dbUser = new UserAuth({
userType,
email,
firstName: fName,
lastName: lName,
password,
});
dbUser.save();
res.json({ message: `Success!` });
}
return;
};
客户端Post:
export const registerAccount = (newAccount: RegisterConfigs) => {
const baseURL = `http://localhost:4000`;
const apiURL = `${baseURL}/userAuth/register`;
const { userType, email, fName, lName, password, confirmPassword } =
newAccount;
const body = {
userType: userType === UserType.employee ? 'Employee' : 'Employer',
email: email.text,
firstName: fName.text,
lastName: lName.text,
password: password.text,
confirmPassword: confirmPassword.text,
};
console.log(JSON.stringify(body));
axios
.post(apiURL, JSON.stringify(body), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods':
'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers':
'x-access-token, Origin, X-Requested-With, Content-Type, Accept',
},
})
.then((response: any) => {
console.log(response);
})
.catch((error: any) => {
console.log(error.toJSON());
});
};
正如您在我的代码中看到的,我正在使用 express.urlencoded({ extended: true });, express.static('public');, express.json ());中间件。我不确定问题出在哪里,我也尝试将 header 的 content-type 更改为 application/json,但仍然遇到这个问题。
根据 derpirscher in 的建议,解决方案是删除 {}
以获得 async (req, res ) => ...
。
我使用了中间件,但仍然无法从请求中得到 undefined。我在客户端使用 axios POST 方法。这是我的代码。
app.ts:
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import userAuth from './routes/userAuth';
const app = express();
dotenv.config();
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use(express.json());
app.use(cors());
app.use('/userAuth', userAuth);
const CONNECTION_URL = process.env.MONGO_CONNECTION_URL!;
const PORT = process.env.PORT || 4000;
mongoose
.connect(CONNECTION_URL)
.then(() => {
app.listen(PORT, () =>
console.log(`Server is running on port ${PORT}`),
);
})
.catch((error) => {
console.log(error);
});
./route/userAuth.ts:
import { Router } from 'express';
import { register } from '../controllers/userAuth';
const router = Router();
router.post('/register', register);
export default router;
../controllers/userAuth:
import mongoose from 'mongoose';
import { Router as router, ErrorRequestHandler } from 'express';
import UserAuth from '../models/userAuthScema';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
export const register: ErrorRequestHandler = async ({ req, res }) => {
console.log(req);
if (!req) {
res.json({ message: `Req Undefined.` });
return;
}
let { userType, email, fName, lName, confirmPassword } = req.body;
let { password } = req.body;
const takenEmail = await UserAuth.findOne({ email });
const passwordValidationFailed = password !== confirmPassword;
if (takenEmail) res.json({ message: `User email has already been used.` });
else if (passwordValidationFailed)
res.json({ message: `Fail password validation.` });
else {
password = await bcrypt.hash(password, 10);
const dbUser = new UserAuth({
userType,
email,
firstName: fName,
lastName: lName,
password,
});
dbUser.save();
res.json({ message: `Success!` });
}
return;
};
客户端Post:
export const registerAccount = (newAccount: RegisterConfigs) => {
const baseURL = `http://localhost:4000`;
const apiURL = `${baseURL}/userAuth/register`;
const { userType, email, fName, lName, password, confirmPassword } =
newAccount;
const body = {
userType: userType === UserType.employee ? 'Employee' : 'Employer',
email: email.text,
firstName: fName.text,
lastName: lName.text,
password: password.text,
confirmPassword: confirmPassword.text,
};
console.log(JSON.stringify(body));
axios
.post(apiURL, JSON.stringify(body), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods':
'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers':
'x-access-token, Origin, X-Requested-With, Content-Type, Accept',
},
})
.then((response: any) => {
console.log(response);
})
.catch((error: any) => {
console.log(error.toJSON());
});
};
正如您在我的代码中看到的,我正在使用 express.urlencoded({ extended: true });, express.static('public');, express.json ());中间件。我不确定问题出在哪里,我也尝试将 header 的 content-type 更改为 application/json,但仍然遇到这个问题。
根据 derpirscher in {}
以获得 async (req, res ) => ...
。