javascript - 在服务器上运行的代码在本地主机上运行时会出错
问题描述
要重新创建代码,只需按照这篇文章
最终代码是:
'use strict';
// Imports dependencies and set up http server
const
express = require('express'),
bodyParser = require('body-parser'),
app = express().use(bodyParser.json()); // creates express http server
// Sets server port and logs message on success
app.listen(process.env.PORT || 1337, () => console.log('webhook is listening'));
// Creates the endpoint for our webhook
app.post('/webhook', (req, res) => {
let body = req.body;
// Checks this is an event from a page subscription
if (body.object === 'page') {
// Iterates over each entry - there may be multiple if batched
body.entry.forEach(function(entry) {
// Gets the message. entry.messaging is an array, but
// will only ever contain one message, so we get index 0
let webhook_event = entry.messaging[0];
console.log(webhook_event);
});
// Returns a '200 OK' response to all requests
res.status(200).send('EVENT_RECEIVED');
} else {
// Returns a '404 Not Found' if event is not from a page subscription
res.sendStatus(404);
}
});
app.get('/webhook', (req, res) => {
// Your verify token. Should be a random string.
let VERIFY_TOKEN = "<YOUR_VERIFY_TOKEN>"
// Parse the query params
let mode = req.query['hub.mode'];
let token = req.query['hub.verify_token'];
let challenge = req.query['hub.challenge'];
// Checks if a token and mode is in the query string of the request
if (mode && token) {
// Checks the mode and token sent is correct
if (mode === 'subscribe' && token === VERIFY_TOKEN) {
// Responds with the challenge token from the request
console.log('WEBHOOK_VERIFIED');
res.status(200).send(challenge);
} else {
// Responds with '403 Forbidden' if verify tokens do not match
res.sendStatus(403);
}
}
});
获取请求路线工作正常,但是当我用这个请求发帖时
curl -H "Content-Type: application/json" -X POST "localhost:1337/webhook" -d '{"object": "page", "entry": [{"messaging": [{"message": "TEST_MESSAGE"}]}]}'
尽管 json 有效,但我收到此错误
SyntaxError: Unexpected token o in JSON at position 1
这对我来说很意外,此代码适用于安装了相同节点版本的服务器 - 14.7.6
解决方案
推荐阅读
- php - php mysql - 不插入字符串值
- r - 闪亮的应用程序未使用我的用户定义函数显示绘图
- google-sheets - 基于范围的谷歌电子表格条件多行格式
- php - woocommerce 如果特定产品在购物车中,则禁用否则需要的特定结帐字段
- javascript - 在javascript中使用map或reduce将二维数组转换为对象
- gatsby - 如何更改我的 Gatsby 博客文章页面的生成路径?
- .net-core - 使用 Nancy 和 .Net Core 时如何在外部程序集中注册 FluentValidation 验证器?
- jira - 无法创建 Confluence 页面,知道为什么吗?
- c# - 检查文件是否存在不起作用
- jquery - 带有有效数据的数据表警告