问题描述
我目前正在学习CRUD,我已经制作了一个简单的react应用程序,您可以在其中使用MongoDB创建,编辑和删除笑话。目前,这与在我自己的PC上运行并通过localhost进行连接的MongoDB配合正常,但现在我想将我的react前端上传到共享的托管站点,并使后端在Atlas上运行。我已经在Atlas上创建了一个集群,但老实说我不知道如何修改当前代码以连接到Atlas而不是localhost。
这是我的一个react组件的样子:(使用localhost设置),但是它们看起来都非常相似,因此,如果我可以使该组件正常工作,那么我应该能够使其全部正常工作。
import React,{ useEffect,useState } from 'react';
import { Link } from 'react-router-dom';
const Create = () => {
const [jokes,setJokes] = useState([]);
useEffect(() => {
const apiUrl = "http://localhost:3000/jokes";
fetch(apiUrl)
.then((res) => res.json())
.then((jokes) => {
setJokes(jokes);
});
},[]);
function createData() { // Used in onclick event further down
const Textarea1 = document.getElementById("Textarea1")
const Textarea2 = document.getElementById("Textarea2")
fetch('http://localhost:3000/jokes/',{
headers: { "Content-Type": "application/json; charset=utf-8" },method: 'POST',body: JSON.stringify({
overskrift: Textarea1.value,jokeTekst: Textarea2.value,})
})
console.log("joke created")
alert("Joke has been created")
window.location.href = "/Admin";
}
return (
<div className="container jokecreate">
<div className="row text-center">
<div className="col-3"></div>
<div className="col-6">
<div><h2>Create New Joke</h2></div>
<form>
<div class="form-group">
<textarea class="form-control" id="Textarea1" rows="1" placeholder="Name of joke" required></textarea>
</div>
<div class="form-group">
<textarea class="form-control" id="Textarea2" rows="3" placeholder="Joke text" required></textarea>
</div>
</form>
</div>
<div className="col-3"></div>
</div>
<div>
<Link to="/Admin"> <button type="button" class="btn btn-success">Back</button> </Link>
<button type="button" onClick={createData} class="btn btn-primary">Create</button>
</div>
</div>
)
}
export default Create
这是我从地图集获得的连接信息:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://****:****@cluster0.cdem6.mongodb.net/jokes?retryWrites=true&w=majority";
const client = new MongoClient(uri,{ useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
其中包含具有读写访问权限的用户的用户名和密码(在此处带有****)。
所以我的问题是我可以将其合并到当前代码中以使其按原样工作,还是需要更多步骤才能使其全部正常工作?
在此先感谢您的帮助或提示。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)