Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: request is not defined

Im trying to replicate a facebook messenger bot but keep getting request is not defined.

Same code as facebook:

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      console.log("Successfully sent generic message with id %s to recipient %s", 
        messageId, recipientId);
    } else {
      console.error("Unable to send message.");
      console.error(response);
      console.error(error);
    }
  });  
}

My node server.js looks like this:

const express = require('express');
const bodyParser = require('body-parser');
//const request = express.request;
const PAGE_ACCESS_TOKEN = 'abc';

let app = express();

app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

[...]

function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}

function callSendAPI(messageData) {..}

[...]

Am I missing something with express? Thanks

like image 973
Sylar Avatar asked Feb 20 '17 18:02

Sylar


3 Answers

This example is making use of third-party Request module.

You could also use the native request like so: require('http').request(), if you want to, but I would say, that the request module is very common, and a good tool to use.

Your request, which is commented out, points to express.request. If used like request() will throw an error, since it's not a function. So, you should really use the Request module, or adjust the code to use native http.request.

Update 2020

The request module is deprecated now, so if you are reading this answer, use the native module or find a popular third-party library like Axios or others.

like image 89
hlfrmn Avatar answered Nov 08 '22 19:11

hlfrmn


You have not installed request module.

First install it npm install --save request and then include it var request = require('request');

like image 39
Ashwani Panwar Avatar answered Nov 08 '22 21:11

Ashwani Panwar


I got the same error but in a different context than yours; when I tried importing

import { Request } from 'express'

export class UserRequest extends Request {
  user: UserEntity;
}

the problem was caused because of using class instead of interface

like image 1
Jood80 Avatar answered Nov 08 '22 19:11

Jood80