My JavaScript code belike
try {
const response = await fetch('saveManualDocs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ docsdata: docs })
});
if (!response.ok) throw new Error('net work error');
const result = await response.json();
console.log('success:', result);
} catch (error) {
console.error('error:', error);
}
My Handler belike this
def doPost(request, session):
import json
try:
# 获取并解析 JSON 请求体
body = request['data']
data = json.loads(body)
if 'docsdata' in data and isinstance(data['docsdata'], dict) and data['docsdata']:
return {'status': 200, 'message': '接收成功'}
else:
return {'status': 404, 'message': '缺少有效的 docsdata'}
except Exception as e:
return {'status': 404, 'message': '请求处理失败: {}'.format(str(e))}
It looks like it should work correctly but it actually errors out and the browser reports 500,
http://*******/system/webdev/resource_center/UserManual/1742/saveManualDocs net::ERR_ABORTED 500 ( Server Error)
Also, I would recommend putting your script in a script library function if you're going to import libraries (so that they are imported once on script restart rather than every time this runs). Even more so however, in this case, I would recommend using system.util.jsonDecode(). No need to import libraries.
There are a couple things wrong with this script.
The try/except statements is causing your errors to not surface. After removing this you will see errors on the gateway logs.
the json loads is causing the first error. There is no need for this import. The request is already converted to a dictionary.
Your return dictionary needs to have the content type.
This script below does not fix the exception error if one arises. But should get you going in the right direction.
try:
# 获取并解析 JSON 请求体
body = request['data']
#data = json.loads(body)
if 'docsdata' in body and isinstance(body['docsdata'], dict) and body['docsdata']:
return {'json':{'status': 200, 'message': u'接收成功'}}
else:
return {'json':{'status': 404, 'message': u'缺少有效的 docsdata'}}
except Exception as e:
return {'json':{'status': 404, 'message': u'请求处理失败: {}'.format(str(e))}}
Marcus didn't call it out but you also must prefix all string literals in Ignition (which is just Python 2) with u if they contain non-ASCII characters: 'message': u'接收成功'} not 'message': '接收成功'}