Following the getting started documentation for Amplify Flutter REST API, the auto-generated POST request below for ExpressJS results in the following error:
SyntaxError: Unexpected token ‘ in JSON at position 1
at JSON.parse
The GET request returns fine, but when changing to POST and adding the body
field below from the documentation the error is returned. How can a POST request be successfully called from Flutter using the Amplify REST API?
Flutter GET Request – (no error)
Future<void> callAPI() async {
try {
RestOptions options = RestOptions(
path: '/example',
apiName: 'ExpressJSRESTAPI'
);
RestOperation restOperation = Amplify.API.get(
restOptions: options
);
RestResponse response = await restOperation.response;
print('GET call succeeded');
print(new String.fromCharCodes(response.data));
} on ApiException catch (e) {
print('GET call failed: $e');
}
}
Flutter POST Request (throws error)
Future<void> callAPI() async {
try {
RestOptions options = RestOptions(
path: '/example',
body: Uint8List.fromList("{'name':'Mow the lawn'}".codeUnits),
apiName: 'ExpressJSRESTAPI'
);
RestOperation restOperation = Amplify.API.post(
restOptions: options
);
RestResponse response = await restOperation.response;
print('POST call succeeded');
print(new String.fromCharCodes(response.data));
} on ApiException catch (e) {
print('POST call failed: $e');
}
}
ExpressJS GET request path
app.get('/example', function(req, res) {
// Add your code here
res.json({success: 'get call succeed!', url: req.url});
});
ExpressJS POST request path
app.post('/example', function(req, res) {
// Add your code here
res.json({success: 'post call succeed!', url: req.url, body: req.body})
});