我有3个文件。 1. server.js - >拥有所有包并运行此文件中的所有代码 2. friends.js - >是一个模块,它携带一个数组,其中包含来自客户端的所有推送数据 3. apiRoutes.js - >是一个路由模块,其任务是执行路由/ api / friends以显示来自friends.js的json对象
当我将friends.js模块和apiRoutes.js模块导入server.js时,它无法识别来自friends.js的friends数组 **
我们如何在路由时访问friends.js中的数据 / api / friends我们运行server.js时的朋友
Server.js:
// server.js
//Incorporate dependencies
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
// console.log(htmlRoutes);
//call express
var app = express();
//requiring htmlRoute.js
require('../app/routing/htmlRoutes.js')(app, path);
//requiring apiRoutes.js
require('../app/routing/apiRoutes.js')(app);
// Declare a port
var PORT = 3000;
//data parsing
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
//requiring the friends.js
require('../app/data/friends.js')
//Listen to port
app.listen(PORT, ()=>{
console.log('listening to PORT: '+ PORT);
});
friends.js
// friends.js
// array of objects
module.exports = function(app){
var friends =[
{
routeName: "ahmed",
name:"Ahmed",
photourl:"https://media.licdn.com/mpr/mpr/shrinknp_400_400/p/6/005/064/1bd/3435aa3.jpg",
questions:[
5,
1,
4,
4,
5,
1,
2,
5,
4,
1
]
}
]
//retreiving stored objects with person's data
app.post("/survey", function(req, res){
var incomingPerson = req.body;
incomingPerson.routeName = incomingPerson.name.replace(/\s+/g, "").toLowerCase();
console.log(incomingPerson);
// friends.push(person);
})
}
apiRoutes.js
// apiRoutes.js
//PARAMETERIZATION
module.exports = function(app){
//A GET route with the url `/api/friends`. This will be used to display a JSON of all possible friends.
app.get("/api/friends/:whoDoIWantToSee?", function(req, res){
var chosen = req.params.whoDoIWantToSee;
res.json(friends);
// if(chosen){
// res.json(friends.chosen);
// }
// console.log(chosen);
});
//A POST routes `/api/friends`. This will be used to handle incoming survey results. This route will also be used to handle the compatibility logic.
}
答案 0 :(得分:0)
您可以从friends.js模块中导出// array of objects
const friends = [
{
routeName: "ahmed",
name:"Ahmed",
photourl:"https://media.licdn.com/mpr/mpr/shrinknp_400_400/p/6/005/064/1bd/3435aa3.jpg",
questions:[
5,
1,
4,
4,
5,
1,
2,
5,
4,
1
]
}
];
module.exports = function(app){
//retreiving stored objects with person's data
app.post("/survey", function(req, res){
var incomingPerson = req.body;
incomingPerson.routeName = incomingPerson.name.replace(/\s+/g, "").toLowerCase();
console.log(incomingPerson);
// friends.push(person);
});
return friends;
};
module.exports.friends = friends;
数组,如下所示:
friends
然后,在您想要访问单身const friends = require('./friends.js').friends;
数组的任何地方,您都可以这样做:
month = newVal;