我创建了一个 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()
中取出 header ,即使发送的信息是 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}"
}
最佳答案
事实证明,我需要做的是对发送数据之前创建的 JSON 对象进行字符串化。所以只是做
nlapiRequestURL("https://somelink.herokuapp.com/", JSON.stringify(json));
工作完美!
关于javascript - 解析从 Netsuite 到 Heroku 的 JSON HTTP 请求返回错误 "SyntaxError: Unexpected token p",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906092/