【发布时间】:2017-06-13 20:24:37
【问题描述】:
我创建了一个 Portlet 表单脚本,它接受参数,将其提交到适当的 Suitelet,然后将生成的 JSON 从 Netsuite 转发到 Node.js Heroku 服务器以进行进一步处理。
我创建的 json 很好,并且返回了正确的值,但是当它发送请求时,heroku 日志给了我错误 SyntaxError: Unexpected token p。
奇怪的是,当我在本地运行服务器并通过 Postman 发送时,这一切都很好。当我通过引起问题的 Netsuite 请求发送所有内容时。它也可能与正文解析器有关,因为错误引用正文解析器。 我觉得这个answer 是在正确的轨道上,但它最终没有帮助。关于如何纠正的任何想法?
处理 JSON 和请求的 Suitelet POST 请求:
var json = {
"par": {
"id":request.getParameter("custpage_id"),
"num":request.getParameter("custpage_num")
},
"in": {
"headers":temp.toString()
}
};
for (var i = 0; i < info.length; i++){
var newVal = "val" + (i+1);
json.in[newVal] = info[i];
}
nlapiRequestURL("https://somelink.herokuapp.com/", json, {"Content-Type":"application/json"});
Heroku 代码:
app.use(cors());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
var server = app.listen(process.env.PORT || 8080, function() {
var port = server.address().port;
console.log('port #: ', port);
});
app.post('/', function( req, res) {
console.log(JSON.stringify(req.headers));
console.log(req.body);
});
完全错误:
SyntaxError: Unexpected token p
at parse (/app/node_modules/body-parser/lib/types/json.js:83:15)
at invokeCallback (/app/node_modules/raw-body/index.js:262:16)
at /app/node_modules/body-parser/lib/read.js:116:18
at done (/app/node_modules/raw-body/index.js:251:7)
at IncomingMessage.onEnd (/app/node_modules/raw-body/index.js:307:7)
at emitNone (events.js:86:13)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
编辑: 应该打印出来的 JSON 如下。这通过 Postman 有效,但通过 Netsuite 发送时无效:
{
"par": {
"id": "customID",
"num": "132"
},
"in": {
"headers": "Item,Current",
"val1": "98696,7938",
"val2": "58839,936"
}
}
更新:
经过更多测试后,我从nlapiRequestURL() 中取出了标头,即使发送的信息是JSON,请求默认为"content-type":"application/x-www-form-urlencoded; charset=UTF-8"。更新后的请求如下所示:
nlapiRequestURL("https://somelink.herokuapp.com/", json);
The Heroku POST request code now:
app.post('/', function( req, res) {
console.log(JSON.stringify(req.headers));
console.log(JSON.stringify(req.body));
});
这会发送 JSON,但格式错误。我得到以下内容,而不是应该在我的编辑中显示的 JSON:
{
"par": "{id=customID,num=132}",
"in": "{headers=Item,Current, val1=98696,7938, val2=58839,936}"
}
【问题讨论】:
-
这可能取决于这些
request.getParameter("custpage_id").. 他们的价值观是什么? -
@suraj 它们是用户输入的字符串值。数字只是一个数字,id 只是一个字符串。虽然 JSON 完美呈现
-
那么 JSON 是什么样子的?那些
console.log()调用实际上打印出什么? -
他们不打印任何东西,就是这样。它应该像我通过 Postman 发送时一样打印出常规的 JSON 内容。我会用更多细节更新我的问题
标签: javascript json node.js heroku suitescript