Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

some test code with mongodb and backend #7

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions campus-connect-react/backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions campus-connect-react/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"author": "Byte-Force",
"license": "ISC",
"dependencies": {
"axios": "^1.4.0",
"express": "^4.18.2",
"mongodb": "^5.7.0",
"nodemon": "^3.0.1"
Expand Down
47 changes: 46 additions & 1 deletion campus-connect-react/backend/server.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,48 @@
//set server.js
const express = require('express');
const app = express();
const port = 3000;app.listen(port, () => console.log(`Server listening on port ${port}!`));
const port = 3000;
const axios = require('axios');
const {MongoClient} = require('mongodb');

const url = 'mongodb+srv://fengj5:[email protected]/?retryWrites=true&w=majority';
const client = new MongoClient(url);

// app.use(express.json());
// app.use((req, res, next) => {
// res.setHeader("Access-Control-Allow-Origin", "https://fengj5.eastus.cloudapp.azure.com/node");
// // res.setHeader("Access-Control-Allow-Origin", "http://localhost:5173");

// res.setHeader(
// "Access-Control-Allow-Headers",
// "Origin, X-Requested-With, Content-Type, Accept"
// );
// res.setHeader(
// "Access-Control-Allow-Methods",
// "GET, POST, PATCH, DELETE, OPTIONS, PUT"
// );

// next();
// });

app.get('/db', async (req, res) => {
// connect to database and call news api with axios https://newsapi.org/v2/everything?q=us&apiKey=43940c2d527346fda96ecbbee77ca1bb
try{
await client.connect();
const database = client.db('CampusConnect');
// console log all collections name in database
const collections = await database.listCollections().toArray();
console.log(collections);
//console log the version of mongodb
const serverInfo = await database.command({buildInfo: 1});
console.log(serverInfo.version);

}
catch (error) {
console.error(error);
res.status(500).json({ error: 'An error occurred while fetching data.' });
} finally {
await client.close();
}
});
app.listen(port, () => { console.log(`Server listening on port ${port}`); });