【问题标题】:AngularJS, NodeJS: save data to a Json file or a databaseAngularJS、NodeJS:将数据保存到 Json 文件或数据库
【发布时间】:2020-12-26 21:23:11
【问题描述】:

我是 AngularJS 和 nodeJS 的新手而且我似乎找不到我需要的信息,我希望这里有人可以提供帮助。 我正在创建这个小应用程序作为培训,它基本上是一个个人词典:用户(现在,只有我)可以输入他们想要保留的所有信息,并在需要时参考。

我的问题是存储部分,即数据库。 我选择了一个简单的 json 文件,我可以很容易地阅读我的 AngularJS 应用程序。但是当我需要存储一个新条目时,麻烦就来了。 经过一番阅读后,我意识到 POST 请求无法正常工作,因为 javascript、angularjs 或 nodejs 不允许写入本地文件(或一般情况下),我需要通过另一个服务来实现这一点.对吗?

我最好分享我的不同文件:

1/ 我的 index.html 调用表单指令:

    <div class="container" ng-controller="EntryController as ctrl">
        <entry-form data="ctrl.entry" submit="ctrl.submitEntry();"></entry-form>
    </div>

2/ 我的表单指令:

function entryForm () {
    return {
        restrict: 'E',
        scope: {},
        bindToController: {
            data: '=',
            submit: '&',
        },
        controller: 'FormController as form',
        templateUrl: 'templates/entry-form.html'
    };
};


angular
    .module('app')
    .directive('entryForm', entryForm);

3/ 我的表单模板:

<form name="orderForm" ng-submit="form.onSubmit()">
    <input required="" ng-minlength=2 ng-maxlength=15 name="title" type="text" ng-model="form.data.title" placeholder="Title">
    <input required="" name="topic" type="text" ng-model="form.data.topics" placeholder="Topic1">
    <input name="topic" type="text" ng-model="form.data.topics" placeholder="Topic2">
    <input name="topic" type="text" ng-model="form.data.topics" placeholder="Topic3">
    <textarea required="" name="text" ng-model="form.data.content" placeholder="Content" name="" id="" cols=42 rows="5"></textarea>
    <input name="link" type="text" ng-model="form.data.link" placeholder="Link">
    <input required="" name="category" type="text" ng-model="form.data.mainCategory" placeholder="Main category">
    <button type="submit">Submit</button>
</form>

4/ 我的表单控制器:

function FormController () {
    this.onSubmit = function () {
        console.log('submitting at formController level')
        this.submit();
    };
};

angular
    .module('app')
    .controller('FormController', FormController);

5/ 我的模型控制器:

function EntryController ($http) {
    const ctrl = this;
    const API = '../database/lexicon.json';

    this.entry = {
    title: "",
    topics: [],
    content: "",
    link: "",
    mainCategory: ""
    };
    this.submitEntry = function () {
        // communicate with the API
        console.log("testing");
        console.log(this.entry);
        $http
        .post(API, "hello my friend")
        .then(function() {
            console.log("successful");
        });
    };
};


angular
    .module('app')
    .controller('EntryController', EntryController);

6/ 我的词典控制器:

function LexiconController ($http) {
    const ctrl = this;
    const API = '../database/lexicon.json';
    this.lexicon = [];
    $http
        .get(API)
        .then(function (response) {
            ctrl.lexicon = response.data.entries;
        });
};

angular
    .module('app')
    .controller('LexiconController', LexiconController)

我希望我没有错过任何东西,否则请告诉我。 当然,我的POST方法不起作用,返回一个405 (Method Not Allowed)

你会建议我如何去做,以便用户可以对该 json 文件执行所有必要的 CRUD 操作? (顺便说一下,数据是我手动输入的)

{
    "entries": [{
        "title": "testing",
        "topics": [],
        "content": "",
        "link": "",
        "mainCategory": "Rails"
        },{
        "title": "Trying again",
        "topics": [],
        "content": "",
        "link": "",
        "mainCategory": "AngularJS"
    }]
}

谢谢!

【问题讨论】:

    标签: javascript node.js json angularjs post


    【解决方案1】:

    我会看看lowdb,这正是它的设计目的。

    例如,假设一个文件“entries.json”:

    entries.json

    {
        "entries": [{
            "title": "testing",
            "topics": [],
            "content": "",
            "link": "",
            "mainCategory": "Rails"
            },{
            "title": "Trying again",
            "topics": [],
            "content": "",
            "link": "",
            "mainCategory": "AngularJS"
        }]
    }
    

    test.js

    const low = require('lowdb')
    const FileSync = require('lowdb/adapters/FileSync')
    
    const dbFileName = "entries.json";
    const adapter = new FileSync(dbFileName)
    const db = low(adapter)
    
    // Add another entry
    db.get('entries')
    .push({
        "title": "Here's a new entry",
        "topics": [],
        "content": "",
        "link": "",
        "mainCategory": "Node.js"
        })
    .write();
    
      
    

    这最终看起来像这样:

    {
    "entries": [
        {
          "title": "testing",
          "topics": [],
          "content": "",
          "link": "",
          "mainCategory": "Rails"
        },
        {
          "title": "Trying again",
          "topics": [],
          "content": "",
          "link": "",
          "mainCategory": "AngularJS"
        },
        {
          "title": "Here's a new entry",
          "topics": [],
          "content": "",
          "link": "",
          "mainCategory": "Node.js"
        }
    ]
    }
    

    【讨论】:

    • 太好了,这是一个非常有用的库 :-)
    • 是的,它看起来像。但是我遇到了另一个问题。当我使用您的示例并在终端中启动 test.js 时,一切正常。但是当我将相同的过程集成到我的控制器中,并使用 ``` npx http-server -o ``` 启动应用程序时,我收到一条错误消息:require is not defined 也许我应该为此打开一个新主题。
    • 啊,是的,您可能需要使用 import 语句而不是 require 语句,我发布的示例是使用 Node.js,它使用 CommonJS 模块而不是 ES6 模块。例如使用 import low from 'lowdb' 而不是 low = require("lowdb");
    • 谢谢!我按照你写的方式试过了,喜欢这样。 import { low } from 'lowdb'; import { FileSync } from 'lowdb/adapters/FileSync'; 它不工作。我收到此错误:Cannot use import statement outside a module 不用担心,我会查一下,您已经帮了很多忙了!
    猜你喜欢
    • 2017-07-23
    • 2017-10-25
    • 2020-12-17
    • 2012-03-27
    • 2013-04-06
    • 2018-09-27
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多