问题
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
回答1:
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.
回答2:
You have not installed request
module.
First install it npm install --save request
and then include it var request = require('request');
来源:https://stackoverflow.com/questions/42351983/referenceerror-request-is-not-defined