Node.js

267

Solutions

367

Contributors

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Share tech news, updates, or what's on your mind.

Sign up to Post

I have a node.js express web application I’d like to covert to a native app for iOS and Android so that I can use the smartphone Bluetooth interface to connect to peripheral devices (Raspberry Pi and/or Arduino). I’d like to develop one app for both iOS and Android and am proficient with JavaScript so am leaning towards React Native, although I have no experience with React. I’m also considering Swift and Flutter. I’d like to develop in my IDE of choice, VS Code, if possible.
This project is foremost for learning so a long learning curve is not an issue. Main considerations are leveraging my web application dev experience and learning new tech that will last.
Any input is welcome!
0
11/26 Forrester Webinar: Savings for Enterprise
11/26 Forrester Webinar: Savings for Enterprise

How can your organization benefit from savings just by replacing your legacy backup solutions with Acronis' #CyberProtection? Join Forrester's Joe Branca and Ryan Davis from Acronis live as they explain how you can too.

In my node app I have to insert a new XMLnode for identify it later. I developed some code where I expected the right result.
It is really simple:

var xmlDoc = new DOMParser().parseFromString(dataRegelWerk);  //Incomming data
if(allok == false){
                var root = xmlDoc.documentElement;

                var varselem = xmlDoc.getElementsByTagName('vars')[0];
                var newEle = xmlDoc.createElement('TCafe');
                var att1 = xmlDoc.createAttribute("initvalue");
                att1.value = "1";
                var att2 = xmlDoc.createAttribute("type");
                att2.value = "int";
                newEle.setAttributeNode(att1);
                newEle.setAttributeNode(att2);

                root.insertBefore(newEle, varselem);
            }

var myFile = serializer.serializeToString(xmlDoc); //Put back to string to store in db

Open in new window


This is the original formatted XML

<xml xmlns:xi="http://www.w3.org/2001/XInclude">

   <vars>
....

Open in new window


I tried to insert before "vars" and the result is

<xml xmlns:xi="http://www.w3.org/2001/XInclude">

    <TCafe initvalue="1" type="int"/><vars>

Open in new window


But I expected

<xml xmlns:xi="http://www.w3.org/2001/XInclude">

    <TCafe initvalue="1" type="int"/>

       <vars>

Open in new window


Is there anything wrong with my code or do I expect a wrong thing? Maybe I have to close the new XMLNode? (I expected the last / will do it.
Any help will be great.
0
I  have a node.js API and a next.js frontend application. The login is working for the most part. But if I open google dev tools and I change the value of the token cookie and try to access the secret page again, it still lets me. Shouldn't it kick me out because the token is no longer the same?

Here is the backend where I check login credentials and then create the token.

exports.login = async (req, res, next) => {
  // check if email exists
  const user = await User.findOne({ email: req.body.email });
  if (!user)
    return res.status(400).send({ errors: ["Invalid login credentials"] });

  //email exists, check password
  const validPass = await bcrypt.compare(req.body.password, user.password);
  if (!validPass)
    return res.status(400).send({ errors: ["Invalid login credentials"] });

  // create jwt token
  const token = jwt.sign(
    { email: user.email, _id: user._id },
    process.env.TOKEN_SECRET,
    { expiresIn: "1h" }
  );
  // add token to header
  res.header("auth-token", token).send(token);
};

Open in new window

Then here is the frontend code for the login where I set the cookie with the token value from the server:

  handleSubmit = async event => {
    const { email, password } = this.state;
    event.preventDefault();
    const user = {
      email,
      password
    };
    // client side validation
    const errors = this.validate(user);
    this.setState({ errors: errors || {} });
    if (errors) return;

    try {
      const response = await login(user);
      const token = response.data;
      cookies.set("token", token);
    } catch (ex) {
      if (ex.response) {
        const errors = ex.response.data.errors;
        this.setState({ errors });
      }
    }
  };

Open in new window

Then I created a route which you can only access if logged in:

Secret.getInitialProps = async ctx => {
  await handleAuthSSR(ctx);
  const response = await axios.get("http://localhost:8000/api/user");

  return {
    users: response.data
  };
};

Open in new window

Here is the auth function (I am using next-cookies)

import nextCookie from "next-cookies";

export const handleAuthSSR = ctx => {
  const { token } = nextCookie(ctx);

  if (ctx.req && !token) {
    ctx.res.writeHead(302, { Location: "/login" });
    ctx.res.end();
    return;
  }
  if (!token) {
    console.log("no token found");
    Router.push("/");
  }

  return token;
};

Open in new window

0
Here's my code in full:

require("dotenv").config();
const { validationResult } = require("express-validator/check");
const mongoose = require("mongoose");
const Profile = require("../models/profile");
const ClientId = process.env.CLIENTID;
const Secret = process.env.SECRET;
const Callback = process.env.CALLBACK;

//this is the empID you're getting from AHA
const empID = 7747;

//get today's date
let date_ob = new Date();

// current date
// adjust 0 before single digit date
let date = ("0" + date_ob.getDate()).slice(-2);

// current month
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);

// current year
let year = date_ob.getFullYear();

// prints date in YYYY-MM-DD format
let today = year + "-" + month + "-" + date;

const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
  clientId: ClientId, //client_id
  clientSecret: Secret, //client secret
  apiVersion: "1.2" // 1.2 is the default
});

exports.getCallback = (req, res, next) => {
  const yesterday_raw = new Date(new Date().setDate(new Date().getDate() - 1));
  const yesterday = yesterday_raw.toISOString().slice(0, 10);

  client.getAccessToken(req.query.code, Callback).then(result => {
    var requests = [
      client.get("/profile.json", result.access_token), //0
      client.get("/activities/date/today.json", result.access_token), //1
      //client.get("/sleep/date/" + yesterday + ".json", result.access_token), //2
      client.get("/sleep/date/today.json", 

Open in new window

0
Here's what I've got:

client.get("/sleep/date/2019-11-05.json", result.access_token), //2

...and this generates an array. One of the values in that array is "REM" and I retrieve it like this:

const rem_sleep = JSON.stringify(data[2][0].summary.stages.rem); //minutes in deep REM sleep

Here's my dilemma: The user may not have worn their Fitbit to bed last night and when that happens, "rem_sleep" will be returned as "undefined."

I don't want that. Especially since I need a valid digit to enter into the database this project is going to be hooked up to.

So, here's what I tried:

const deep_sleep = JSON.stringify(data[2][0].summary.stages.rem); //minutes in deep REM sleep
        if (deep_sleep > 0) {
          const rem_sleep = deep_sleep;
        } else {
          const rem_sleep = 0;
        }
        res.send(rem_sleep);

As you might suspect, "rem_sleep" comes back as undefined .

I'm learing that with JavaScript, constants stay credible within the scope of their particular "block."

That said, how can I pull this off?

I need whatever it is that I can do in Javascript that equates to an IF clause that provides me a genuine value and not something that comes back "undefined."

What do you think?
0
Here's what I'm using to get yesterday's date:

const yesterday_raw = new Date(new Date().setDate(new Date().getDate() - 1));
console.log(yesterday_raw);

It works fine, but I need to format it according to YYYY-MM-DD. I've seen a number of approaches on the Internet, but they all look kind of clunky.

I figured I would bring it before the ninjas and see if someone's got an easy way of formatting the above as YYYY-MM-DD.

Thoughts?
0
Here's the array I'm getting back from Fitbit...

{"summary":{"water":0},"water":[]}

This is part of a much larger body of data. I'm retrieving it using this:

res.send(data[4][0]);

My question is two-fold: First I want to get to the "0" value. From what I understand, "summary" is an Object based on the way it's documented using curly braces. Within that Object, I have both Properties and Values. Properties can be arrays within themselves which is what I have here. I have a "summary" Object with two properties, both of which are called, "water." One is a Property with a single value, the other is an Array.

If I want to get to the first "water" property that has a value of "0," I would think I would do this:

res.send(data[4][0].water

...correct? The response I get is "[]."

If I do this:

res.send(data[4][0]["water"]);

I get "[]."

Why? I would expect "res.send(data[4][0].water" to give me "0," and it doesn't.

Why not?
0
Here's the array:

[
   {
      "activities": [
         {
            "activeDuration": 1280000,
            "activityLevel": [
               {
                  "minutes": 0,
                  "name": "sedentary"
               },
               {
                  "minutes": 3,
                  "name": "lightly"
               },
               {
                  "minutes": 10,
                  "name": "fairly"
               },
               {
                  "minutes": 9,
                  "name": "very"
               }
            ],
            "activityName": "Walk",
            "activityTypeId": 90013,
            "averageHeartRate": 88,
            "calories": 134,
            "duration": 1280000,
            "elevationGain": 0,
            "hasGps": false,
            "heartRateLink": "https://api.fitbit.com/1.2/user/-/activities/heart/date/2019-11-07/2019-11-07/1sec/time/05:10:57/05:32:17.json",
            "heartRateZones": [
               {
                  "max": 82,
                  "min": 30,
                  "minutes": 3,
                  "name": "Out of Range"
               },
               {
                  "max": 114,
                  "min": 82,
                  "minutes": 19,
                  "name": "Fat Burn"
               },
               {
                  "max": 139,
                  "min": 114,
                  "minutes": 0,
                  "name": "Cardio"
               },
               {
                  

Open in new window

0
I'm building a Fitbit API and we're going great guns but I've run into a snag and I'm confident it's due to my being new to Node.js.

This works:

exports.getCallback = (req, res, next) => {
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback')
	.then(result => { 
	// use the access token to fetch the user's profile information
	//client.get("/profile.json", result.access_token)
	client.get('/activities/date/2019-11-07.json', result.access_token)
		.then(results => {
			console.log(results[0].goals.calories);
			//res.send(results[0]);
		}).catch(err => {
			const error = new Error(err);
			error.httpStatusCode = 500;
			return next(error);
		});
		
	});
};

Open in new window


...and this works:

exports.getCallback = (req, res, next) => {
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback')
	.then(result => { 
	// use the access token to fetch the user's profile information
	//client.get("/profile.json", result.access_token)
		client.get("/activities/calories/date/today/1d.json", result.access_token)
		.then(answers => {
			.then(answers => {
			res.send(answers[0]["activities-calories"][0].value);
		}).catch(err => {
			const error = new Error(err);
			error.httpStatusCode = 500;
			return next(error);
		});
	});
};

Open in new window


Now, are you ready for this?

I've got to retrieve information that's coming from multiple endpoints. So, I tried to do this:

exports.getCallback = (req, res, next) => {
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback')
	.then(result => { 
	// use the access token to fetch the user's profile information
	//client.get("/profile.json", result.access_token)
	client.get('/activities/date/2019-11-07.json', result.access_token)
		.then(results => {
			console.log(results[0].goals.calories);
			//res.send(results[0]);
		}).catch(err => {
			const error = new Error(err);
			error.httpStatusCode = 500;
			return next(error);
		});
		[b]client.get("/activities/calories/date/today/1d.json", result.access_token)
		.then(answers => {
			.then(answers => {
			res.send(answers[0]["activities-calories"][0].value);
		}).catch(err => {
			const error = new Error(err);
			error.httpStatusCode = 500;
			return next(error);
		});[/b]
	});
};

Open in new window


And I get this error:

         .then(answers => {
                        ^

SyntaxError: Unexpected token .

I'm assuming it's because I'm going about this the wrong way.

I need two sets of information, one from "client.get(activities)' and one from "client.get('activites/calories')."

How do I make that happen?
0
I'll open up a Node application, make some changes and then...

I'll get an error that says:  Error: listen EADDRINUSE: address already in use :::3000

I'll go to my Command Line and enter: netstat -aon. I'll get a list of ports and who's using what and I'll find Port 3000, make a note of the PID and then do something like this:

Taskkill/PID <PID number> /F

I'll get a message that says the process has been killed and I'll move on from there.

But I'm at a point where I can't even do CNTRL C and kill my server so I can upload a package or whatever I need to do. I'll use "process exit" and then my Git Bash will stop responding and I have to start all over.

I'm getting things done, but I wanted to reach out and get some other eyes on this to figure out if there's something wrong that I need to fix. On other computers, I don't have that problem, but there's something awry here and I don't know what.

Thoughts?
0
Success in ‘20 With a Profitable Pricing Strategy
Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

I'm working my way through fitbit-node and I'm trying to understand how I can access various pieces of information that go beyond the "profile," which I've been able to successfully retrieve,  but I need calories burned, heartbeat etc and that's where I'm getting lost.

First of all, here's the working code:

// initialize the express application
const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const token="";

//const authorizeRoutes = require("./routes/authorize");

app.use(bodyParser.json());
//app.use("/authorize", authorizeRoutes);

// initialize the Fitbit API client
const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
	clientId: "BOGUS", //client_id
	clientSecret: "BOGUS_AGAIN", //client secret
	apiVersion: '1.2' // 1.2 is the default
});

// redirect the user to the Fitbit authorization page
app.get("/authorize", (req, res) => {
	// request access to the user's activity, heartrate, location, nutrion, profile, settings, sleep, social, and weight scopes
	res.redirect(client.getAuthorizeUrl('activity heartrate location nutrition profile settings sleep social weight', 'http://localhost:3000/callback')); //callback url
});

// handle the callback from the Fitbit authorization flow (working code)
app.get("/callback", (req, res) => {
	// exchange the authorization code we just received for an access token
	

Open in new window

0
I want to utilize some "best practices" as I build the API you see below, as far as using routes, models and controllers etc.

The code below is something I'm using from "fitbit-node." It works just fine, however. I want to take some of what resonates as that which belongs in a "routes" directory and move it so, when I'm all finished, I can upload it as something that looks and feels like a complete and accurate app.

At least, that's what I'm thinking.

Here's my code:

// initialize the express application
const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
[b]//const authorizeRoutes = require("./routes/authorize");[/b]

app.use(bodyParser.json());
[b]//app.use("/authorize", authorizeRoutes);[/b]

// initialize the Fitbit API client
const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
	clientId: "CLIENT_ID", //client_id
	clientSecret: "SECRET", //client secret
	apiVersion: '1.2' // 1.2 is the default
});

// redirect the user to the Fitbit authorization page
app.get("/authorize", (req, res) => {
	// request access to the user's activity, heartrate, location, nutrion, profile, settings, sleep, social, and weight scopes
	res.redirect(client.getAuthorizeUrl('activity heartrate location nutrition profile settings sleep social weight', 'http://localhost:3000/callback')); //callback url
});

// handle the callback from

Open in new window

0
I'm working my way through a couple of tutorials that walk you through how to create an API that retrieves Fitbit info. The content is great and every educational, but I'm stuck and I need some help.

First of all, I'm using  "fitbit-node" (https://github.com/lukasolson/fitbit-node). With that, I've been able to successfully retrieve "profile.json" which seems to be the starting point for any API.

The "app.js" that's included as part of the example, looks like this:

// initialize the express application
const express = require("express");
const app = express();

// initialize the Fitbit API client
const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
	clientId: "22BD5D", //client_id
	clientSecret: "9677a6cdf63836e26d0617e9ac2c38f8", //client secret
	apiVersion: '1.2' // 1.2 is the default
});

// redirect the user to the Fitbit authorization page
app.get("/authorize", (req, res) => {
	// request access to the user's activity, heartrate, location, nutrion, profile, settings, sleep, social, and weight scopes
	res.redirect(client.getAuthorizeUrl('activity heartrate location nutrition profile settings sleep social weight', 'http://localhost:3000/callback')); //callback url
});

// handle the callback from the Fitbit authorization flow
app.get("/callback", (req, res) => {
	// exchange the authorization code we just received for an access token
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback').then(result => { 

Open in new window

0
I'm working with a fully functional Node.js code that interacts with the Fitbit API.

Being somewhat new to Node, however, has me in a spot where I need a little guidance.

The code looks like this:

// initialize the express application
const express = require("express");
const app = express();

// initialize the Fitbit API client
const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
	clientId: "CLIENT_ID", //client_id
	clientSecret: "CLIENT_SECRET", //client secret
	apiVersion: '1.2' // 1.2 is the default
});

// redirect the user to the Fitbit authorization page
app.get("/authorize", (req, res) => {
	// request access to the user's activity, heartrate, location, nutrion, profile, settings, sleep, social, and weight scopes
	res.redirect(client.getAuthorizeUrl('activity heartrate location nutrition profile settings sleep social weight', 'http://localhost:3000/callback')); //callback url
});

// handle the callback from the Fitbit authorization flow
app.get("/callback", (req, res) => {
	// exchange the authorization code we just received for an access token
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback').then(result => { //callback url
		// use the access token to fetch the user's profile information
		[b]client.get("/profile.json", result.access_token)[/b]
		[u]//client.get ("/1/user/[user-id]/[resource-path]/date/[date]/[period].json", result.access_token)[/u]
		.then(results => {
			res.send(results[0]);

Open in new window

0
I'm using "npm fitbit-node" and I am poised on the threshold of great things!

Here's the "app.js" file and I've emboldened that section of the code that I've got a question about:

// initialize the express application
const express = require("express");
const app = express();

// initialize the Fitbit API client
const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
	clientId: "CLIENT_ID", //client_id
	clientSecret: "CLIENT_SECRET", //client secret
	apiVersion: '1.2' // 1.2 is the default
});

// redirect the user to the Fitbit authorization page
app.get("/authorize", (req, res) => {
	// request access to the user's activity, heartrate, location, nutrion, profile, settings, sleep, social, and weight scopes
	res.redirect(client.getAuthorizeUrl('activity heartrate location nutrition profile settings sleep social weight', 'http://localhost:3000/callback')); //callback url
});

// handle the callback from the Fitbit authorization flow
app.get("/callback", (req, res) => {
	// exchange the authorization code we just received for an access token
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback').then(result => { //callback url
		// use the access token to fetch the user's profile information
		[b]client.get("/profile.json", result.access_token)[/b]
		[u]//client.get ("/1/user/[user-id]/[resource-path]/date/[date]/[period].json", result.access_token)[/u]
		.then(results => {
			res.send(results[0]);
			

Open in new window

0
I've tried 3000, 8080 and 8000 and no matter which port I try, I get the same error message:

events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::8000

I've tried killall, I've tried restarting my system, I've got no clue how to fix this thing and I can't move a muscle. I've got to figure this out!

Does anyone have any ideas?
0
I am trying to set a cookie with Node.js and express but when I check in chrome dev tools there is no cookie. I am obviously doing something wrong but not sure what.

In my loginController.js I have

exports.postLogin = async (req, res) => {
  const { email, password } = req.body;
  const user = await authenticate(email, password);
  if (!user) return res.status(403).send("Invalid email or password");
  const userData = {
    name: user.name,
    email: user.email,
    type: AUTH_USER_TYPE
  };
  res.cookie("token", userData, { httpOnly: true, signed: true });
  res.json(userData);
};

Open in new window


And in app.js I have:

const cookieParser = require("cookie-parser");
app.use(cookieParser(process.env.COOKIE_SECRET));

Open in new window

0
I'm working through a Node tutorial and this one particular lecture is prefaced with a disclaimer that says Windows users needed to alter the course content code a little bit in order to successfully upload an image.

I did that, but the result is something that I can't even find on Google so I'm appealing to my ever ready pool of IT Ninjas at EE and seeing if you recognize this mess and can tell me where I've gone south.

Here's my app.js  file. The relevant code is in bold.

const path = require("path");

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
[b]const multer = require("multer");
const uuidv4 = require("uuid/v4");[/b]

const feedRoutes = require("./routes/feed");

const app = express();

[b]const fileStorage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, "images");
  },
  filename: function(req, file, cb) {
    cb(null, uuidv4());
  }
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpg" ||
    file.mimetype === "image/jpeg"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};[/b]

app.use(bodyParser.json());
[b]app.use(
  multer({ storage: fileStorage, fileFilter: fileFilter }).single("image")
);[/b]
app.use("/images", express.static(path.join(__dirname, "images")));

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    

Open in new window

0
What is it about Node that makes it difficult if not impossible to host on a shared server?

I'm assuming it's because you have to be able to log directly into the server using SSH, but why? What is it about Node that requires that kind of approach?
1
How to Generate Services Revenue the Easiest Way
How to Generate Services Revenue the Easiest Way

This Tuesday! Learn key insights about modern cyber protection services & gain practical strategies to skyrocket business:

- What it takes to build a cloud service portfolio
- How to determine which services will help your unique business grow
- Various use-cases and examples

The following code works just fine:

app.use((req, res, next) => {
  if (!req.session.user) {
    return next();
  }
  User.findById(req.session.user._id)
    .then(user => {
      if (!user) {
        return next();
      }
      req.user = user;
      next();
    })
    .catch(err => {
      throw new Error(err);
    });
});

Open in new window


 I'm just wondering what the difference is between next(); and return next();

The way that I've seen it explained on the web is that when you write "return next();" you're "...compelling your app to stop the execution of the code once the callback is completed."

The first thing that's happening is I'm looking for the presence of a session id. If one is not present, I'm thinking that "next" in this case is referring to the User.findById dynamic, yes? And because it's coded alongside "return," that definitively routes the code to the next piece.

Yes?

You wouldn't HAVE to write "return," but it's a good practice, especially in this instance correct?

But here's where I start getting a little fuzzy.

You're now in the "User.findById" piece and if you dop't find a user you get "return next();." Well, what is "next?"

I might be misinterpreting "next" to mean the next piece of the surrounding code.

Bottom line: I'm a little confused as to what "next" means and the difference between using "return next" and simply "next."

Can you help a brother out?
0
hi

how can i remove a node from html collection xml in javascript
0
Hello Experts

I am looking for a little direction on a project.  It may be preference, but how do you all start and go about writing your code?


The project will use node, express and mySql with a a react/handlebar front.  The user will add, update, view and report on records of entry.  


Do you start with your front side user entry skeleton? Or do you start with the back side getting the database connected and the server created and work forward?


Thanks,
Ed
0
Here's my code:

require("dotenv").config();

const express = require("express");
const mongoose = require("mongoose");
const csrf = require("csurf");
const bodyParser = require("body-parser");

const app = express();
const conn = process.env.CONNECTION;
const csrfProtection = csrf();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(csrfProtection);

const loginRoutes = require("./routes/login");
const authRoutes = require("./routes/auth");
const createRoutes = require("./routes/create");

app.use((req, res, next) => {
  res.locals.csrfToken = req.csrfToken();
  next();
});

app.use(loginRoutes);
app.use(authRoutes);
app.use(createRoutes);

mongoose
  .connect(conn)
  .then(result => {
    app.listen(5000);
  })
  .catch(err => {
    console.log(err);
  });

Open in new window


I'm getting an error that says my csrf token is misconfigured and I don't know what to do or where to start.

Here's the whole error:

Error: misconfigured csrf
    at csrf (C:\wamp\www\authentication\node_modules\csurf\index.js:71:19)
    at Layer.handle [as handle_request] (C:\wamp\www\authentication\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\wamp\www\authentication\node_modules\express\lib\router\index.js:317:13)
    at C:\wamp\www\authentication\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\wamp\www\authentication\node_modules\express\lib\router\index.js:335:12)
    at next 

Open in new window

0
Please advise what steps are required to create web search page enabling micro services based engineering pattern.
Working on nodejs and react project.
0
I'm using Postman to build an API in Node. Here's a portion of my Controller:

 const first_name = req.body.first_name;

Easy, enough...

The thing is, I'm getting a message in Postman that says: "TypeError: Cannot read property &#39;first_name&#39; of undefined<br> &nbsp; &nbsp;at exports.postCreate (C:\wamp\www\authentication\controllers\create.js:9:23)"

Here's the way I've got my Postman dynamic set up:

postman screenshot
Why is Postman not seeing what I'm assuming are my form fields?
0

Node.js

267

Solutions

367

Contributors

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Top Experts In
Node.js
<
Monthly
>