I am newbie to neo4j. I am using javascript driver . Need to know what i am doing wrong . I am attaching code snippet . Am I missing something ?
Please guide me.
app.js
var express = require('express');
var bodyParser = require('body-parser');
var neo4j = require('neo4j-driver').v1;
var app = express();
app.use(bodyParser.json());
var driver = neo4j.driver('bolt://localhost', neo4j.auth.basic("neo4j", "neo4j"));
var session = driver.session();
session
.run('MERGE (alice:Person {name : {nameParam} }) RETURN alice.name AS name', {nameParam: 'Alice'})
.subscribe({
onNext: function (record) {
console.log(record.get('name'));
},
onCompleted: function () {
session.close();
},
onError: function (error) {
console.log(error);
}
});
/* Start the express App and listen on port 8080 */
var initServer = function () {
var server = app.listen(8080);
console.log('info', '*********** Application Server is listening on Port 8080 ***********');
};
initServer();
error :
I briefly bumped into the same problem earlier today. But then I remembered that when I started the neo4j server earlier, I had navigated to http://localhost:7474 from the browser and signed in using the default credentials username=neo4j and password=neo4j, which then prompted me to create a new password before I could proceed.
My hunch is that you probably have not changed the default password, which you need to. After that, you should have no problem with authentication. Use the short program below you check if you are good. Create a file index.js and add this:
const neo4j = require('neo4j-driver').v1;
const driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "YOUR_NEW_PASSWORD"));
const session = driver.session();
const personName = 'Alice';
session.run(
'CREATE (a:Person {name: $name}) RETURN a',
{name: personName})
.then(result => {
session.close();
const singleRecord = result.records[0];
const node = singleRecord.get(0);
console.log(node.properties.name);
// on application exit:
driver.close();
})
.catch(error => console.log(error));
The using nodejs, simply execute this from the command prompt:
node index.js
You should see the output "Alice" on the command line
Related
I created a flutter project with a web version and we already have a server for database access that another android/ios app uses. However the web version of the new app is running into problems with cors policy. I've been trying to solve this looking at other stock overflow questions and searching on google without success and was hoping someone can help me figure out what I might be doing wrong.
I've tested making the uri client side both with:
String url = "https://" + host + ":" + port;
Uri uri = Uri.parse(url + "/test");
and
String url = host + ":" + port;
Uri uri = Uri.https(url, "/test");
I then call the server using the http/http package:
Response response = await get(uri).timeout(const Duration(seconds: 17));
As for the structure of the server side code:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const https = require('https');
const routerOne = require('./path/to/router/file');
const routerTwo = require('./path/to/router/file');
const dotenv = require('dotenv');
const fs = require("fs");
dotenv.config();
console.log('port' + process.env.PORT);
var key = fs.readFileSync('./certs/key.key');
var cert = fs.readFileSync('./certs/cert.crt');
var options = {
key: key,
cert: cert
};
const cors = require('cors');
const app = express();
app.use(cors());
try {
let server = https.createServer(options, app);
server.listen(process.env.PORT, () => {
console.log('Started https server on port ' + process.env.PORT);
});
} catch (err) {
console.log(err);
}
app.get('/test', cors(), function (req, res, next) {
res.json({msg: "This is CORS-enabled for all origins!"})
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({limit: '50mb', extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/router/one', routerOne);
app.use('/router/two', routerTwo);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
console.log(err);
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Unlike android when running web version(Chrome or Edge), I have been unable to get the response from the newly added '/test' on the server side. I'm hoping for some suggestion for how I can get the cors policy to work.
Client side I've tried using Uri.https instead of Uri.parse and I added headers as well.
On the server I tried to follow instructions on how to add cors policy to node.js/express.
Error message from flutter:
Error: XMLHttpRequest error.
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 963:28 get current
packages/http/src/browser_client.dart 69:22 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1685:54 runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18 handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 766:44 handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 795:13 _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 557:7 [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1530:7 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14 _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39 dcall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37309:58 <fn>
at Object.createErrorWithStack (http://localhost:59072/dart_sdk.js:5093:12)
at Error._throw (http://localhost:59072/dart_sdk.js:20399:18)
at Error.throwWithStackTrace (http://localhost:59072/dart_sdk.js:20396:18)
at async._AsyncCallbackEntry.new.callback (http://localhost:59072/dart_sdk.js:40921:18)
at Object._microtaskLoop (http://localhost:59072/dart_sdk.js:40778:13)
at _startMicrotaskLoop (http://localhost:59072/dart_sdk.js:40784:13)
at http://localhost:59072/dart_sdk.js:36261:9
Image of browser: image of browser with network tab
Update Solution
The answer from Ber is correct. This is a problem with certificate. Self signed certificate was being used on our server and by getting a new certificate using Let's encrypt the problem got solved. If anyone else runs into the "XMLHttpRequest error" they may also want to check out the error output in the browser as the "net::ERR_CERT_AUTHORITY_INVALID" was not shown in flutter.
The error code in your screen shot is net::ERR_CERT_AUTHORITY_INVALID
meaning the server's SSL certificate is expired, invalid for the domain or not accepted by the root certificates in your app.
I created a really simple bookstore with a Books, Customer, and a main service. This particular problem involves the main and books service.
I'm currently making a gRPC request called: "createBook", which creates a book in our DB, and also console logs.
When running the gRPC server (booksServer) without docker, the process runs smoothly.
But as soon as I use docker, it seems as if a gRPC request doesn't go into the gRPC server...
By "using docker" I mean using docker to run the booksServer. (As shown below)
Result: Without Docker
As you can see, without docker, the request is fulfilled, and everything works as it should.
Our gRPC client makes a call to the gRPC server (in which metadata is created) and the metadata is also sent back to the client.
(Scroll down to see the gRPC server file with the method called "getBooks".)
booksServer (without docker)
*** Notice the console logs in the booksServer!!! ***
Let me run the booksServer (with docker)
(Dockerfile below)
FROM node:12.14.0
WORKDIR /usr/src/app
COPY package*.json ./
COPY . /usr/src/app
RUN npm install
RUN npm install nodemon -g
EXPOSE 30043
CMD ["nodemon", "booksServer.js"
Here's my main service docker file too which initiates the request:
FROM node:12.14.0
WORKDIR /usr/src/app
COPY package*.json ./
COPY . /usr/src/app
# COPY wait-for-it.sh .
# RUN chmod +x /wait-for-it.sh
RUN npm install
EXPOSE 4555
CMD ["node", "main.js"]
^^^ Notice how when dockerfile is used to run booksServer
it doesn't go/run inside the booksServer file
***It does NOT produce any console.logs when I fire off a gRPC requesst***
This is what the booksServer.js file looks like
Heres the Books Stub
//use this for bookInitiator
const path = require('path');
const PROTO_PATH = path.join(__dirname, "../protos/books.proto");
const grpc = require("grpc");
const protoLoader = require("#grpc/proto-loader");
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true,
longs: String,
enums: String,
arrays: true
});
const BooksService = grpc.loadPackageDefinition(packageDefinition).BooksService;
// potential issues to fix 1) making localhost port dynamic 2) docker containerization may cause conflict
const client = new BooksService (
"172.17.0.2:30043",
grpc.credentials.createInsecure()
);
console.log("Creating stub inside booksStub");
module.exports = client;
Here's the gRPC Server file (with the binded ports).
// const PROTO_PATH = "../protos/books.proto";
const path = require('path');
const PROTO_PATH = path.join(__dirname, './protos/books.proto');
const grpc = require("grpc");
const protoLoader = require("#grpc/proto-loader");
const express = require("express");
const controller = require("./booksController.js");
const app = express();
app.use(express.json());
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true,
longs: String,
enums: String,
arrays: true,
});
const booksProto = grpc.loadPackageDefinition(packageDefinition);
const { v4: uuidv4 } = require("uuid");
const server = new grpc.Server();
server.addService(booksProto.BooksService.service, {
CreateBook: (call, callback) => {
console.log("call to CreateBook");
//sample will take the call information from the client(stub)
const book = {
title: call.request.title,
author: call.request.author,
numberOfPages: call.request.numberOfPages,
publisher: call.request.publisher,
id: call.request.id,
};
controller.createBook(book);
let meta = new grpc.Metadata();
meta.add("response", "none");
console.log("metadata in createBook...: ", meta);
call.sendMetadata(meta);
callback(
null,
//bookmodel.create
{
title: `completed for: ${call.request.title}`,
author: `completed for: ${call.request.author}`,
numberOfPages: `completed for: ${call.request.numberOfPages}`,
publisher: `completed for: ${call.request.publisher}`,
id: `completed for: ${call.request.id}`,
}
);
},
GetBooks: (call, callback) => {
console.log("call to GetBooks");
// read from database
let meta = new grpc.Metadata();
meta.add('response', 'none');
call.sendMetadata(meta);
controller.getBooks(callback);
}
});
server.bind("0.0.0.0:30043", grpc.ServerCredentials.createInsecure());
console.log("booksServer.js running at 0.0.0.0:30043");
console.log("Inside Books Server!");
console.log("call from books server");
server.start();
horus.js (custom made simple tracing tool),
grab trace grabs the journey of a certain request
and sends it back to the gRPC client as metadata
const fs = require("fs");
const grpc = require("grpc");
const path = require("path");
class horus {
constructor(name) {
this.serviceName = name; // represents the name of the microservices
this.startTime = null;
this.endTime = null;
this.request = {};
this.targetService = null; // represents the location to which the request was made
this.allRequests = []; // array which stores all requests
this.timeCompleted = null;
this.call;
}
static getReqId() {
// primitive value - number of millisecond since midnight January 1, 1970 UTC
// add service name/ initials to the beginning of reqId?
return new Date().valueOf();
}
// start should be invoked before the request is made
// start begins the timer and initializes the request as pending
start(targetService, call) {
this.startTime = Number(process.hrtime.bigint());
this.request[targetService] = "pending"; // {books: 'pending', responseTime: 'pending'}
this.request.responseTime = "pending";
this.targetService = targetService;
this.call = call;
this.request.requestId = horus.getReqId();
}
// end should be invoked when the request has returned
end() {
this.endTime = Number(process.hrtime.bigint());
this.request.responseTime = (
(this.endTime - this.startTime) /
1000000
).toFixed(3); //converting into ms.
this.sendResponse();
this.request.timeCompleted = this.getCurrentTime();
}
// grabTrace accepts inserts trace into request
// trace represents the "journey" of the request
// trace expects metaData to be 'none when the server made no additional requests
// trace expects metaData to be the request object generated by the server otherwise
// in gRPC, the trace must be sent back as meta data. objects should be converted with JSON.parse
grabTrace(metaData) {
//console.log("incoming meta data ", metaData);
console.log("Inside Grab Trace Method.");
console.log("Metadata inside grabTrace: ", metaData);
if (metaData === "none" || metaData === undefined) this.request[this.targetService] = "none";
else {
metaData = JSON.parse(metaData);
this.request[this.targetService] = metaData;
}
this.allRequests.push(this.request);
this.sendResponse();
}
// displayRequests logs to the console all stored requests
// setTimeout builds in deliberate latency since metadata may be sent before or after a request is done processing
displayRequests() {
console.log("\n\n");
console.log("Logging all requests from : ", this.serviceName);
this.allRequests.forEach((request) => {
console.log("\n");
console.log(request);
});
console.log("\n\n");
}
// sends response via metadata if service is in the middle of a chain
sendResponse() {
if (
this.request.responseTime === "pending" ||
this.request[this.targetService] === "pending" ||
this.call === undefined
)
return;
console.log("Inside send response");
let meta = new grpc.Metadata();
meta.add("response", JSON.stringify(this.request));
console.log('meta in send response: ', meta)
this.call.sendMetadata(meta);
}
writeToFile() {
console.log("call to writeToFile");
console.log("logging request obj ", this.request);
let strRequests = "";
for (let req of this.allRequests) {
// First write to file - contains Total
// subsequent - chained requests
strRequests += `Request ID: ${req.requestId}\n`;
strRequests += `"${
Object.keys(req)[0]
}" service -> Response received in ${Object.values(req)[1]} ms (Total)\n`;
strRequests += `Timestamp: ${req.timeCompleted}\n`;
// while we don't hit an empty object on the 1st key, go inside
// add numbering in order for nested requests inside original?!
let innerObj = Object.values(req)[0];
while (innerObj !== "none") {
strRequests += `"${
Object.keys(innerObj)[0]
}" service -> Response received in ${Object.values(innerObj)[1]} ms\n`;
strRequests += `Timestamp: ${innerObj.timeCompleted}\n`;
innerObj = Object.values(innerObj)[0];
}
strRequests +=
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
}
console.log('strRequests', strRequests)
fs.writeFile(this.serviceName + 'data' + '.txt', strRequests, { flag: "a+" }, (err) => {
if (err) {
console.error(err);
}
}); //'a+' is append mode
}
module.exports = horus;
main.js (initiates gRPC client request)
const path = require('path');
// const grpc = require("grpc");
const customersStub = require("./stubs/customersStub.js");
const booksStub = require("./stubs/booksStub.js");
const horusTracer = require(path.join(__dirname, "./horus/horus.js"));
//In master branch
console.log("Stub is Inside main service!!!");
const book = {
title: "ITttttt",
author: "Stephen King",
numberOfPages: 666,
publisher: "Random House",
id: 200,
};
const bookId = {
id: 200
}
const customer = {
id: 123,
name: "Lily",
age: 23,
address: "Blablabla",
favBookId: 100
};
const customerId = {
id: 123
}
let ht = new horusTracer("main");
function CreateBook () {
ht.start('books')
booksStub.CreateBook(book, (error, response) => {
if (error) console.log("there was an error ", error);
ht.end();
ht.displayRequests();
ht.writeToFile();
}).on('metadata', (metadata) => {
console.log("Before grab trace is invoked!");
ht.grabTrace(metadata.get('response')[0]);
});
}
}
CreateBook(); //Works
What I think is the issue.
Edit: murgatroid99 mentioned that it was a networking issue with docker!
~~~~~~~~~
I initially thought this was a networking issue, but I don't think it is
because all my docker files are running on the default bridge network.
So they all technically can communicate with one another...
Is it something wrong with nodemon interacting with Docker?
Does the server not output the console logs...?
Is the server actually running and working...?
Do I need a reverse proxy like nginx?
``
The problem is that your server is binding to "127.0.0.1:30043". You say that you are running the docker images using the default bridge network. In that mode the docker image has a different (virtual) network than the host machine has, so its loopback address is different from the host machine's loopback address. To fix that, you can instead bind the server to 0.0.0.0:30043 or [::]:30043to bind to other network interfaces that the client can connect to from outside of the docker container.
For the same reason, connecting the client to localhost:30043 will not work: its "localhost" address also refers to the loopback interface within the docker container. You should instead replace "localhost" with the IP address of the server container.
Alternatively, as described in this question, you can network the docker containers in "host" mode so that they share the same network with the host machine.
I'm new to React and Node and i'm trying to make a simple WebSocket using Socket.IO which gonna simply send greetings to all connected users and the user will respond to the server.
The Node.JS server is running on a Windows PC while the React-Native app is running on both iOS and Android devices.
Node.JS server code is the following
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : 'block',
database : 'visualpos'
});
// Creating a GET route that returns data from the 'users' table.
app.get('/prenotazioni', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query("SELECT Data, Importo_Doc FROM tabella_pagamenti", function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
connection.release();
});
});
app.get('/', function(req, res){
res.send('<h1>Hello World</h1>');
});
// Starting our server.
http.listen(3000, () => {
console.log('In ascolto sulla porta *:3000');
});
io.emit('saluta', 'Ciao dal server :)');
io.on('connected', (data) => {
console.log(data);
});
Actually GET part of the code works perfectly but the Socket.IO seems death.
The client doesn't get any response and server the same i think the Socket.IO server simply doesn't start..
In XCode Debug i get the following errors when the app is running on the iPhone
And i even get on both devices warning "Unrecognized WebSocket connection option(s) 'agent', 'perMessageDeflate',..."
And here is the code i'm using in React-Native
import io from 'socket.io-client'
var socket = io('http://192.168.100.50:3000', {
jsonp: false,
transports: ['websocket'],
autoConnect: true,
reconnection: true,
reconnectionDelay: 500,
reconnectionAttempts: Infinity
});
componentDidMount(){
socket.emit('connected','we');
socket.on('saluta',(data) => { alert(data); });
}
On socket.io getStarted section, they use a "connection" event instead of "connected" (https://socket.io/get-started/chat/).
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
I am using the Google Cloud IoT with Pub/Sub.
I have a device reading sensor data and sending it to a topic in Pub/Sub.
I have a topic cloud function that is triggered by this message and I would like to have the device configuration updated, however I am unable to do so due to the following permission error.
index.js :
/**
* Triggered from a message on a Cloud Pub/Sub topic.
*
* #param {!Object} event The Cloud Functions event.
* #param {!Function} The callback function.
*/
var google = require('googleapis');
//var tt = google.urlshortener('v1');
//console.log(Object.getOwnPropertyNames(google.getAPIs()));
var cloudiot = google.cloudiot('v1');
function handleDeviceGet(authClient, name, device_id, err, data) {
if (err) {
console.log('Error with get device:', device_id);
console.log(err);
return;
}
console.log('Got device:', device_id);
console.log(data);
console.log(data.config);
var data2 = JSON.parse(
Buffer.from(data.config.binaryData, 'base64').toString());
console.log(data2);
data2.on = !data2.on;
console.log(data2);
var request2 = {
name: name,
resource: {
'versionToUpdate' : data.config.version,
'binaryData' : Buffer(JSON.stringify(data2)).toString('base64')
},
auth: authClient
};
console.log('request2' + request2);
var devices = cloudiot.projects.locations.registries.devices;
devices.modifyCloudToDeviceConfig(request2, (err, data) => {
if (err) {
console.log('Error patching device:', device_id);
console.log(err);
} else {
console.log('Patched device:', device_id);
console.log(data);
}
});
}
const handleAuth = (device_id) => {
console.log(device_id);
return (err, authClient) => {
const project_id = 'animated-bonsai-195009';
const cloud_region = 'us-central1';
const registry_id = 'reg1';
const name = `projects / ${project_id} /locations / ${cloud_region} /` +
`registries / ${registry_id} /devices / ${device_id}`;
if (err) {
console.log(err);
}
if (authClient.createScopedRequired &&
authClient.createScopedRequired()) {
authClient = authClient.createScoped(
['https://www.googleapis.com/auth/cloud-platforme']);
}
var request = {
name: name,
auth: authClient
};
// Get device version
var devices = cloudiot.projects.locations.registries.devices;
devices.get(request, (err, data) =>
handleDeviceGet(authClient, name, device_id, err, data));
}
};
exports.subscribe = (event, callback) => {
// The Cloud Pub/Sub Message object.
const pubsubMessage = event.data;
// We're just going to log the message to prove that
// it worked.
var obj = JSON.parse(Buffer.from(pubsubMessage.data, 'base64').toString());
console.log(Buffer.from(pubsubMessage.data, 'base64').toString());
console.log(event);
console.log(Object.getOwnPropertyNames(event));
console.log(callback);
let message = {
"watter": 1
};
message = new Buffer(JSON.stringify(message));
const req = {
name: event.data.deviceId,
resource: message
};
console.log(obj.deviceId);
google.auth.getApplicationDefault(handleAuth(obj['deviceId']));
// Don't forget to call the callback.
callback();
};
package.json :
{
"name": "sample-pubsub",
"version": "0.0.1",
"dependencies": {
"googleapis": "25.0.0"
}
}
Error:
A few options:
Check that you have enabled API access for the Google Cloud IoT Core API for the project used when creating the Google Cloud Function.
Check that you have enabled billing for your project
If you are deploying your Google Cloud Functions with gcloud beta functions deploy ... from the folder with your .js and package.json files, you may want to set the environment variables (GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS) or use gcloud auth application-default login before deploying in case you have multiple Google Cloud projects and need to enable the API on the configured one.
Update This community tutorial shows you how to do this - note that there have been some updates to Google Cloud Functions that require you to use a newer version of the Node JS client library as is done in the NodeJS sample and as corrected in this PR, note the version of the client library in package.json.
Good afternoon everyone.
I'm working on a school project to create an application using the MEAN stack, and I'm having issues with routing.
I'm using the login-and-register application found here as a base for my work : http://jasonwatmore.com/post/2015/12/09/mean-stack-user-registration-and-login-example-tutorial
Basically, I am unable to post data that I get from a form I created to my database.
If I get the creation part to work, then I'll be able to continue working on my project. Here is the code :
The Controller
(function () {
'use strict';
function Controller(UserService, NoteService, FlashService) {
var vm = this;
vm.note = null;
function createNote() {
NoteService.Create(vm.note, vm.user)
.then(function () {
FlashService.Success('Note created');
})
.catch(function (error) {
FlashService.Error(error);
});
}
vm.createNote = createNote;
function initController() {...}
initController();
}
angular.module('app').controller('Home.IndexController', Controller);
}());
And then we have the service I'm calling, NoteService
(function () {
'use strict';
function Service($http, $q) {
var service = {};
function Create(note, user) {
return $http.post('/api/notes', note).then(handleSuccess, handleError);
}
service.Create = Create;
return service;
}
angular
.module('app')
.factory('NoteService', Service);
}());
This is the $http.post function that doesn't work : /api/notes cannot be found (error 404 on browser console) I am sure my object note is getting at least to this request, because adding a console.log(note) just before returns what I want in the console.
On the server side, I have another controller for handling errors :
var noteService = require('services/notes.service');
//routes
router.post('/create', createNote);
module.exports = router;
function createNote(req, res) {
noteService.create(req.body)
.then(function () {
res.sendStatus(200);
})
.catch(function (err) {
res.status(400).send(err);
});
}
the service on the server side to discuss with the data base :
var mongo = require('mongoskin');
var db = mongo.db(config.connectionString, { native_parser: true });
db.bind('notes');
var service = {};
service.create = create;
module.exports = service;
function create(noteParam, userParam) {...}
and my server.js file looks like this :
require('rootpath')();
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({ secret: config.secret, resave: false, saveUninitialized: true }));
// use JWT auth to secure the api
app.use('/api', expressJwt({ secret: config.secret }).unless({ path: ['/api/users/authenticate', '/api/users/register'] }));
// routes
app.use('/login', require('./controllers/login.controller'));
app.use('/register', require('./controllers/register.controller'));
app.use('/app', require('./controllers/app.controller'));
app.use('/api/users', require('./controllers/api/users.controller'));
app.use('/api/notes', require('./controllers/api/notes.controller'));
// make '/app' default route
app.get('/', function (req, res) {
return res.redirect('/app');
});
// start server
var server = app.listen(3000, function () {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
I thought this line in the server.js file : app.use('/api/notes', require('./controllers/api/notes.controller'))
would permit my post request to send my note object to the server side, to '/api/notes') but I'm not quite sure how all this works together.
I am hoping anyone can help me, even though the code I gave was lengthful.
I am just beginning with MEAN and have no idea what I'm doing wrong.
Thanks in Advance for your answer.