如果你想到,在纽瓦特被点击之后,如何把服务器的辅助功能从javascript文档中打上下面的几页。 你们必须利用吉大港山区开发计划的要求,把服务器的侧端点称作终端点。 然后,最后一点要求行使这一职能。 还需要安装灯塔。 使用Npm 表示在依赖性中添加,并安装 no。 • 确保你与MongoDb(我使用法典与大刚果之间的连接)。 修改这一办法,以适应您的具体数据集
服务器档案
import express from express ;
import mongoose from mongoose ;
import cors from cors ;
import dotenv/config ;
const app = express();
mongoose.set( strictQuery , false);
mongoose.connect(
process.env.MONGODB_CONNECT_STRING,
{ useNewUrlParser: true }
);
const db = mongoose.connection;
db.once( open , () => {
console.log( Successfully connected to MongoDB using Mongoose! );
});
app.use(express.json()); // Parse JSON bodies
app.use(cors());
app.get( / , (req, res) => {
res.send( Hello World );
});
app.listen(3000, () => {
console.log( Server is running on port 3000 );
});
// define the schema
const documentSchema = new mongoose.Schema({
id: String,
title: String,
artist: String,
genre: String,
popularity: Number,
date: Date,
});
// Create the Document using the schema
const Document = mongoose.model( Songs , documentSchema);
// Endpoint to create a song
app.post( /create-song , async (req, res) => {
const { title, artist, genre, popularity, date } = req.body; //get in the parameters
try {
await createSong(title, artist, genre, popularity, date); //call the func to upload to database
res.status(200).send( Song created successfully );
} catch (error) {
console.log( Error uploading document: , error);
res.status(500).send( Internal server error );
}
});
// Define the asynchronous function
async function createSong(title, artist, genre, popularity, dateString) {
try {
const date = new Date(dateString);
// Create a new document instance
const document = new Document({ title, artist, genre, popularity, date });
// Save the document to the database
await document.save();
} catch (error) {
throw error;
} finally {
// Close the database connection
mongoose.connection.close();
}
}
j) 电话文件
window.onload = function() {
var title = document.getElementById( title );
var artist = document.getElementById( artist );
var genre = document.getElementById( genre );
var rating = document.getElementById( rating );
var released = document.getElementById( released );
uploadSong();
function uploadSong() {
const songData = {
title: title.value,
artist: artist.value,
genre: genre.value,
popularity: rating.value,
date: released.value
};
fetch( http://localhost:3000/create-song , {
method: POST ,
headers: {
Content-Type : application/json
},
body: JSON.stringify(songData)
})
.then(response => {
if (response.ok) {
console.log( Song created successfully );
} else {
alert( Error: , response.statusText);
}
})
.catch(error => {
alert( Error: , error.message);
});
}
}