问题
I'm trying to create a Facebook messenger bot using NodeJS and Express.
I'm following the facebook guide and when I tried to run this command
curl -H "Content-Type: application/json" -X POST "localhost:4000/" -d '{"object": "page", "entry": [{"messaging": [{"message": "TEST_MESSAGE"}]}]}'
I have got this error SyntaxError: Unexpected token ' in JSON at position 0
Here is my code:
var express = require('express');
var bodyParser = require('body-parser');
var request = require("request")
var app = express();
var port = process.env.PORT || 4000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function(req, res) {
if (req.query['hub.verify_token'] === '22222') {
res.send(req.query['hub.challenge']);
console.log("GET")
res.sendStatus(200)
}
console.log("Error: wrong token")
})
app.post('/', function(req, res) {
messaging_events = req.body.entry[0].messaging;
console.log("post")
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200));
}
}
res.sendStatus(200);
});
app.listen(port, function() {
console.log('Listening on port ' + port);
});
var token = "<token>";
function sendTextMessage(sender, text) {
messageData = {
text: text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: token },
method: 'POST',
json: {
recipient: { id: sender },
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
I ignored this error and started the bot. Webhooks I connected via ngrok. I'm sure that on Facebook I set everything right.But I'm not getting the message information sent to my webhook from facebook.]
Edit: '{"object": "page", "entry": [{"messaging": [{"message": "TEST_MESSAGE"}]}]}'
this is the error line
回答1:
try:
curl -H "Content-Type: application/json" -X POST "localhost:4000/" -d "{""object"": ""page"", ""entry"": [{""messaging"": [{""message"": ""TEST_MESSAGE""}]}]}"
回答2:
try this out:
curl -H "Content-Type: application/json" -X POST "localhost:4000/webhook" -d "{\"object\": \"page\", \"entry\": [{\"messaging\": [{\"message\":\"TEST_MESSAGE\"}]}]}"
use \" because the json parser needs the double quote(" ") for json parsing here we are passing
single quote(' ') that's why the parser failed to parse the json that we are passing
"{\"object\": \"page\", \"entry\": [{\"messaging\": [{\"message\":\"TEST_MESSAGE\"}]}]}"
check this out this will work.
Thanks
来源:https://stackoverflow.com/questions/51754510/facebook-messenger-bot-error-unexpected-token-in-json-at-position-0