clientSide NodeJs中的JSON响应

时间:2017-10-07 20:15:43

标签: node.js

我想从服务器获取.json文件到ClientSide中的.js文件

var fs = require('fs');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({extended: false, limit: '50mb'});
module.exports = function(app){
  app.get('/tables_particular/', function(req, res){

    first = JSON.parse(fs.readFileSync('./database/table.json'))

    res.render('tables_particular', {todos: data.member, 
                                     tbledit: first,
                            });
});

app.post('/tables_particular/', urlencodedParser, function(req, res){

    var exportlist = req.body.detail

    fs.writeFileSync('./database/table.json', exportlist); 
        res.json(exportlist);

});

这里是app.js :(服务器代码)

var express = require('express');

var mShController = require('./controllers/mShController');

var app = express();

//
app.set('view engine', 'ejs');

//static files
app.use(express.static('./public'));

mShController(app);


//listen to port
app.listen(3000);
console.log('You are listening to port 3000');

我需要在javascript文件中使用什么代码来获取json文件。

我在js文件中需要它:

var data = response.tbledit

1 个答案:

答案 0 :(得分:0)

var content;  
var fs = require('fs');
fs.readFile('path/myfile.json', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;

    console.log(content); // HERE DO ANYTHING WITH THE JSON DATA
});

或点击此链接read-json-file-content-with-require-vs-fs-readfile

var myObj = require('path/myfile');
var value = myObj.someValue;
});