gpt4 book ai didi

javascript - 如何在 2 个不同的 React 应用程序中使用同一个数据库

转载 作者:行者123 更新时间:2023-12-03 03:36:57 25 4
gpt4 key购买 nike

我必须制作一个离线应用程序,尽可能与另一个在线应用程序同步。

我使用 PouchDB 开发了离线应用程序。感谢 github 存储库 create-react-app 我创建了这个应用程序。该应用程序在 localhost:3000 上运行。在此应用程序中,我创建并管理一个名为“patentDB”的小数据库。

我使用经典的 put 方法管理数据库,就像我们在文档中看到的那样:

var db = new PouchDB('patientDB')
db.put({
_id: 'dave@gmail.com',
name: 'David',
age: 69
});

使用 PouchDB 提供的 chrome 开发工具,我可以看到数据库按照我想要的方式工作(文档已创建):

Db overview

另一个应用程序是另一个带有节点服务器的 React 应用程序。在开发过程中,该应用程序在 localhost:8080 上运行。在此应用程序中,我尝试使用以下代码获取“patentDB”中包含的所有文档:

const db = new PouchDB('patientDB', { skip_setup: true });
db.info()
.then(() => {
console.log("DBFOUND")
db.allDocs({include_docs: true})
.then(function (result) {
console.log("RESULT" , result)
}).catch(function (err) {
console.log("NOPE")
console.log(err);
});
})

我的问题是我无法在在线应用程序中获取使用离线应用程序创建的“patentDB”。当我执行 var db = new PouchDB ('PatentDB') 时,它会创建一个新的空数据库,因为它找不到已存在的数据库。

我使用谷歌浏览器来运行我的所有应用程序,所以我认为数据库可以共享。

但是我用两个 html 文件做了一些非常简单的测试:

First.html 使用文档初始化新数据库
Second.html 读取 First.html 中创建的数据库
在这种情况下,我可以在 Second.hmtl 中获取使用 First.html 创建的文档,即使它们是两个独立的“网站”。

我认为在本地主机上运行的应用程序就像与应用程序的其余部分隔离一样,即使像我之前所说的那样,我对所有应用程序使用相同的浏览器......

我不知道该怎么做,或者我不知道是否有可能做我想做的事情。如果有人对我有想法,我会很高兴。

<小时/> 编辑

我可以明白为什么我的数据库没有共享:
当我运行 html 文件后查看所有本地数据库时,我可以看到以下内容:
local db

正如我们所见,数据库来自文件_pouch_DB_NAME - file://

当我从本地运行的应用程序(本地主机)检查我的数据库时,我可以看到:
db from localhost

数据库不是来自文件,而是来自localhost:8080
如果您知道我如何从服务器中运行的应用程序中的本地数据库获取文档,这对我来说真的很有帮助!

最佳答案

PouchDB在浏览器中使用IndexedDB,它遵循同源策略。 MDN says this:

IndexedDB adheres to a same-origin policy. An origin is the domain, application layer protocol, and port of a URL of the document where the script is being executed. Each origin has its own associated set of databases. Every database has a name that identifies it within an origin.

因此,您必须将本地数据库复制到中央服务器才能共享数据。这可能是 PouchDB Server与您的节点应用程序一起。您还可以直接从浏览器访问PouchDB Server:

var db = new PouchDB('http://localhost:5984/patientDB')

作为替代方案,您可以使用 CouchDB 或 IBM Cloudant(基本上是托管的 CouchDB)。

关于javascript - 如何在 2 个不同的 React 应用程序中使用同一个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45812787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com