Я сталкиваюсь с этой ошибкой всякий раз, когда пытаюсь сохранить пользователя, когда он подписывается на ключ API в этом API, который я создаю.
Я пытался использовать решения из других вопросов, похожих на мои, но для жизни я не могу найти решение. Любая помощь приветствуется.
Схема пользователя
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
_id: Schema.Types.ObjectId,
email: String,
apikey: String,
});
module.exports.UserSchema = mongoose.model('User', UserSchema, 'User');
Сохранить нового пользователя
const uuidv4 = require('uuid/v4')
const User = require('../schemas/User')
function saveNewUser(email){
let uuid = uuidv4()
let newUser = new User({email: email, apiKey: uuid})
newUser.save((err) => {
if(err) console.log(err)
})
}
module.exports = saveNewUser
компонент, который я пытаюсь использовать в
import {useState} from 'react'
import Layout from "../components/Layout";
import Card from "../components/Card";
import Button from "../components/Button";
import Logo from "../components/Logo";
import Background from "../components/Background";
import Header from "../components/Header";
import TextContent from "../components/TextContent";
import EmailInput from "../components/EmailInput";
import FormGroup from "../components/FormGroup";
import saveNewUser from "../utils/saveNewUser"
const generateNewKey = (props) => {
const [email, setEmail] = useState("");
const onSubmit = e => {
e.preventDefault()
if (email === ''){
console.log('Please enter something')
}
saveNewUser(email)
}
const emailInputOnChange = e =>{
setEmail(e.target.value)
};
return (
<React.Fragment>
<Layout />
<Background />
<Card>
<Logo />
<Header text='Air Stats API' />
<TextContent>
To generate a new API key all we need is your name and email
</TextContent>
<FormGroup onSubmit = {onSubmit}>
<EmailInput
placeholder='Email'
for='email'
onChange={emailInputOnChange}
></EmailInput>
<Button
text='Get API Key'
width='25%'
type="submit"
></Button>
</FormGroup>
</Card>
</React.Fragment>
);
};
export default generateNewKey;
Мой сервер. js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const morgan = require('morgan');
const helmet = require('helmet');
const dotenv = require('dotenv').config();
const apiRouter = require('./routes/ApiRouter');
function connectToDB() {
mongoose.connect(process.env.URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: 'AircraftCharacteristics'
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Connected to DB');
});
}
const loadMiddleware = () => {
// Cross origin resource sharing middleware
app.use(
cors({
origin: ['http://localhost:3000'],
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization']
})
);
// Security middleware
app.use(helmet());
// Morgan set to log all requests
app.use(morgan('common'));
// API router
app.use('/api', apiRouter);
console.log('Middleware Loaded');
};
const startServer = () => {
app.listen(port, () => console.log(`App listening on ${port}`));
};
const app = express();
const port = process.env.PORT;
startServer();
loadMiddleware();
connectToDB();