早上好,我有一个问题,让我在总PLS,我找不到任何方法来解决它的任何地方,没有与谷歌搜索.和chatGPS告诉我配置我的数据库这样的SSL:1)登录您的MongoDB Atlas账户,然后导航到集群的“安全”页面。
2) Click on the "Add IP Address" button to add a new IP address to the authorized access list.
3) In the window that appears, select "Add current IP address" to add your current IP address to the authorized access list.
4) Select "Add another IP address" if you want to add a different IP address.
5) Check the "Enable Access from Anywhere" box to allow access to your cluster from any IP address.
6) Click on the "Add IP Address" button to add the new access rule to your cluster.
7) If your application uses an SSL connection to access the database, you must also add the SSL access rule. To do this, click the "Add CIDR" button and add your web server's IP address, followed by "/32" to specify a 32-bit subnet mask.
8) Check the "Require SSL" box to require all connections to your cluster to use SSL.
9) Click the "Save" button to save the changes.
但我的“添加IP地址”按钮只有字段“访问列表条目:“和“注解:“别的什么也没有,我不知道到哪儿去找它,我一定很傻,但它让我发疯。
这是我的API代码,GET可以工作,POST不行。
import connectDb from '../../../data/db';
import Student from '../../../models/Student';
import { promises as fs } from 'fs';
import path from 'path';
const handler = async (req, res) => {
const { studentId } = req.query;
switch (req.method) {
case 'GET':
try {
const student = await Student.findById(studentId);
if (!student) {
res.status(404).json({
message: `Student with id ${studentId} not found`,
});
} else {
res.status(200).json(student);
}
} catch (error) {
res.status(500).json({ message: error.message });
}
break;
case 'PUT':
res.status(401).json({
message: "You can't do it, delete and create a new student.",
});
break;
case 'DELETE':
try {
const student = await Student.findByIdAndDelete(studentId);
if (!student) {
res.status(404).json({
message: `Student with id ${studentId} not found`,
});
}
const imgPath = path.join(process.cwd(), 'public', student.img);
const cvPath = path.join(process.cwd(), 'public', student.cv);
fs.unlink(imgPath);
fs.unlink(cvPath);
return res.status(200).json({
message: `Student n°${studentId} as been deleted with succes.`,
});
} catch (error) {
res.status(500).json({ message: error.message });
}
break;
default:
res.status(400).json({ message: 'Invalid request method' });
break;
}
};
export default connectDb(handler);
下面是我的表单的代码:
import { useState } from 'react';
import styles from './StudentForm.module.css';
import 'formdata-polyfill';
export default function StudentForm({ refresh, setIsForm }) {
const [name, setName] = useState('');
const [title, setTitle] = useState('');
const [firstName, setFirstName] = useState('');
const [img, setImg] = useState(null);
const [cv, setCv] = useState(null);
const [technologies, setTechnologies] = useState(['']);
// fonction pour gérer la soumission du formulaire
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('name', name);
formData.append('title', title);
formData.append('firstName', firstName);
formData.append('img', img);
formData.append('cv', cv);
formData.append('technologies', JSON.stringify(technologies));
try {
const response = await fetch('/api/students', {
method: 'POST',
body: formData,
});
if (response.ok) {
setName('');
setTitle('');
setFirstName('');
setImg(null);
setCv(null);
setTechnologies(['']);
refresh();
setIsForm(false);
event.target.reset();
} else {
console.error('Erreur lors de la création du student');
}
} catch (error) {
console.error('Erreur lors de la création du student', error);
}
};
const handleTechnologiesChange = (e, index) => {
const newTechnologies = [...technologies];
newTechnologies[index] = e.target.value;
setTechnologies(newTechnologies);
};
const handleAddTechnologies = () => {
setTechnologies([...technologies, '']);
};
return (
<form className={styles.form_container} onSubmit={handleSubmit}>
<div className={styles.form_field}>
<label htmlFor="title" className={styles.label_form}>
Titre :
</label>
<input
className={styles.input_text}
type="text"
name="title"
onChange={(e) => setTitle(e.target.value)}
placeholder="Ex : Développeur C# full stack"
required
/>
</div>
<div className={styles.form_field}>
<label htmlFor="name" className={styles.label_form}>
Nom :
</label>
<input
className={styles.input_text}
type="text"
name="name"
onChange={(e) => setName(e.target.value)}
placeholder="Ex : DOH"
required
/>
</div>
<div className={styles.form_field}>
<label htmlFor="firstname" className={styles.label_form}>
Prénom :
</label>
<input
className={styles.input_text}
type="text"
name="firstname"
onChange={(e) => setFirstName(e.target.value)}
placeholder="Ex : John"
required
/>
</div>
<div className={styles.form_field}>
<label htmlFor="img" className={styles.label_form}>
Image :
</label>
<input
className={styles.input_file}
type="file"
name="img"
onChange={(e) => setImg(e.target.files[0])}
accept="image/*"
required
/>
</div>
<div className={styles.form_field}>
<label htmlFor="cv" className={styles.label_form}>
CV :
</label>
<input
className={styles.input_file}
type="file"
name="cv"
onChange={(e) => setCv(e.target.files[0])}
accept=".pdf"
required
/>
</div>
<div className={styles.form_field}>
<label htmlFor="technologies" className={styles.label_form}>
Technologies:
</label>
{technologies.map((technology, index) => (
<div key={index}>
<input
className={styles.input_text_techno}
type="text"
name="technologies"
value={technology}
placeholder="Ex : C#"
onChange={(e) => handleTechnologiesChange(e, index)}
/>
</div>
))}
<div className={styles.btn_ajout_techno}>
<svg
className={styles.plus_svg}
onClick={handleAddTechnologies}
width="30"
height="30"
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="1.5"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M12 5.75v12.5"></path>
<path d="M18.25 12H5.75"></path>
</svg>{' '}
<span>{'← Ajouter une techno'}</span>
</div>
</div>
<div className={styles.btn_container}>
<button className={styles.btn_submit} type="submit">
Envoyer
</button>
</div>
</form>
);
}
我和bbd的关系:
import mongoose from 'mongoose';
import dotenv from 'dotenv';
dotenv.config();
const db_adress = process.env.REACT_APP_DB_ADDRESS;
const connectDb = (handler) => async (req, res) => {
if (mongoose.connections[0].readyState) {
return handler(req, res);
}
await mongoose
.connect(db_adress, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connexion à MongoDB réussie !'))
.catch(() => console.log('Connexion à MongoDB échouée !'));
return handler(req, res);
};
export default connectDb;
文件存储中间件的配置:
import multer from 'multer';
import path from 'path';
import fs from 'fs';
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const dir = path.join(process.cwd(), 'public', 'documents');
fs.mkdirSync(dir, { recursive: true });
cb(null, dir);
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
cb(
null,
`${file.fieldname}-${uniqueSuffix}${path.extname(
file.originalname.replace(/ /g, '_')
)}`
);
},
});
const upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
const ext = path.extname(file.originalname);
if (
ext !== '.pdf' &&
ext !== '.png' &&
ext !== '.jpg' &&
ext !== '.jpeg'
) {
cb(new Error('File type is not supported.'), false);
return;
}
cb(null, true);
},
});
export default upload;
最后是我的学生:
import mongoose from 'mongoose';
const { Schema } = mongoose;
const StudentSchema = new Schema({
title: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
firstName: {
type: String,
required: true,
},
img: {
type: String,
required: true,
},
cv: {
type: String,
required: true,
},
technologies: {
type: [String],
required: true,
},
});
const Student =
mongoose.models.Student || mongoose.model('Student', StudentSchema);
export default Student;
一切都在本地运行。在localhost中没有问题。
联机时GET方法可以工作,但post返回控制台。错误:“创建学生时出错”和响应json:代码:400 {error“上传文件时出错。"}
求你救我出去我一直在找你。
1条答案
按热度按时间luaexgnf1#
伙计,你的POST在API中不工作?我不明白你的问题...但是,如果POST不工作,API中的方法在哪里?你没有在API中实现这个POST