Как подключить mongoDB в react`е
Такая проблема, что при попытке просто подключить mongoDB в реакте
import React, {Component} from 'react';
export default class App extends Component{
componentDidMount(){
const {MongoClient} = require('mongodb');
const client = new MongoClient('mongodb+srv://dafu4k:****@cluster0.jd26aac.mongodb.net/?retryWrites=true&w=majority');
const start = async () => {
try{
await client.connect();
console.log('Connected')
}
catch(e){
console.log(e)
}
}
start();
}
render(){
return (
<>
<h1>Home page</h1>
</>
)
}
}
В самом браузере появляются ошибки одного вида
Module not found: Error: Can't resolve 'os' in 'C:\Users\DaFu4\OneDrive\Рабочий >стол\mongotest\mongo-test\node_modules\ip\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "os": require.resolve("os-browserify/browser") }'
- install 'os-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "os": false }
Отличия у них в том, что в последней строке разные ключи (timers,crypto,http и тд)
Смотрел как подключить mongoDB к react, везде использовали некий mongoose вместе с mongoDB, вот понять не могу, может для подключения к react он обязателен или я всё таки что то не так делаю? (в обычном js всё хорошо работает, код не менял)
src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
package.json
{
"name": "mongo-test",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"crypto-browserify": "^3.12.0",
"mongodb": "^4.7.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Ответы (1 шт):
Ответ на вопрос тут: https://stackoverflow.com/questions/72539795/how-to-connect-mongodb-in-react Если кратко, то нельзя подключить mongoDB напрямую к реакту, нужно использовать express.js и тд