how does $.post send request from s3 index.html? is it get or post request - amazon-s3

s3 static hosting index.html file has 2 buttons - A , B. Its a simple app for voting, after clicking on either button it sends thru api gateway a value "a" or "b" to lambda backend function; the lambda function puts the value into dynamo db table.
I dont get how "$.post(backend_url...)" works, does it send post or get request? My lambda is made to accept only get request. I specified this code below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A or B?</title>
<base href="/index.html">
<meta name = "viewport" content = "width=device-width, initial-scale = 1.0">
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
</head>
<body>
<div id="content-container">
<div id="content-container-center">
<h3>A or B?</h3>
<form id="choice" name='form' method="POST" action="/">
<button id="a" type="submit" name="vote" class="a" value="a">A</button>
<button id="b" type="submit" name="vote" class="b" value="b">B</button>
</form>
<div id="tip">
you can vote several times
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script>
#url to api gateway
var backend_url = "https://5y7dfynd34.execute-api.us-east-1.amazonaws.com/"
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
$(document).on('click','button[name=vote]',function(){
vote = this.value;
# ************* ********************
#this line below is tricky for me - does it generate POST or GET REQUEST to api gateway?
$.post(backend_url, JSON.stringify({ "vote": vote }), function(result,status){
console.log(result);
if ("success" == status) {
usedButton = $('button.' + vote);
usedButton.prop('disabled', true);
usedButton.html(vote + ' <i class="fa fa-check-circle"></i>');
usedButton.css('opacity','0.5');
unusedButton = $('button.' + (vote == 'a' ? 'b' : 'a'));
unusedButton.prop('disabled', false);
unusedButton.html(vote == 'a' ? 'b' : 'a');
unusedButton.css('opacity','1');
setTimeout(function(){usedButton.prop('disabled', false); usedButton.html(vote);}, 2000);
} else {
alert("error! :(");
}
});
return false;
});
</script>
</body>
</html>

i managed to find and troubleshoot the 500 error. the problem was that the backend lambda was returning 500 status due to its own failed exception management.
basically, the backend lambda could not parse the msg sent from s3!
the post request from s3 already had 'body', the full structure of the post event request:
event = {'version': '2.0', 'routeKey': 'ANY /voting', 'rawPath': '/voting', 'rawQueryString': '', 'headers': {'accept': 'application/json', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9', 'content-length': '123', 'content-type': 'text/plain', 'host': '5y7dfynd34.execute-api.us-east-1.amazonaws.com', 'origin': 'http://frontend-erjan-vote.s3-website-us-east-1.amazonaws.com', 'referer': 'http://frontend-erjan-vote.s3-website-us-east-1.amazonaws.com/', 'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Brave";v="108"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'cross-site', 'sec-gpc': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36', 'x-amzn-trace-id': 'Root=1-63ba8b86-3f15fd0a56aa19646ed508da', 'x-forwarded-for': '164.40.37.179', 'x-forwarded-port': '443', 'x-forwarded-proto': 'https'}, 'requestContext': {'accountId': '025416187662', 'apiId': '5y7dfynd34', 'domainName': '5y7dfynd34.execute-api.us-east-1.amazonaws.com', 'domainPrefix': '5y7dfynd34', 'http': {'method': 'POST', 'path': '/voting', 'protocol': 'HTTP/1.1', 'sourceIp': '164.40.37.179', 'userAgent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'}, 'requestId': 'eaq8-gtAoAMEbkw=', 'routeKey': 'ANY /voting', 'stage': '$default', 'time': '08/Jan/2023:09:23:18 +0000', 'timeEpoch': 1673169798075}, 'body': '{"body":{"MessageAttributes":{"vote":{"Type":"String","StringValue":"a"},"voter":{"Type":"String","StringValue":"count"}}}}', 'isBase64Encoded': False}
in backend lambda i tried to parse it without parsing inner 'body'.
the msg i tried to parse:
{
"body": {
"MessageAttributes": {
"vote": {
"Type": "String",
"StringValue": "b"
},
"voter": {
"Type": "String",
"StringValue": "count"
}
}
}
}
but it had additional 'body'!
"body":
{
"body": {
"MessageAttributes": {
"vote": {
"Type": "String",
"StringValue": "b"
},
"voter": {
"Type": "String",
"StringValue": "count"
}
}
}
}

Related

Access to fetch from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
GET http://127.0.0.1:8000/storage/images/NAMES.pdf net::ERR_FAILED 200
I'm having a problem with the viewing of my PDF.
Whenever I view a photos it does work.
MY FRONTEND:
data return
viewAppointmentFileData: [],
viewAppointmentFilePDFData: [],
<div v-else-if="myAppointment.fileExtension == 'pdf'"
>
<q-btn
class="q-ma-sm"
icon="preview"
color="positive"
#click="openFilePDF(myAppointment)"
label="View"
/>
The viewing of the PDF.
<q-dialog v-model="viewAppointmentFilePDF">
<q-card style="width: 600px; max-width: 80vw">
<div class="q-pa-md">
<pdf
class="q-pa-sm text-center"
:src="
`http://127.0.0.1:8000/storage/images/${viewAppointmentFilePDFData.file}`
"
width="115"
height="115"
/>
</div>
</q-card>
</q-dialog>
My method.
myAppointmentData() {
try {
const bearerToken = localStorage.getItem("Bearer");
this.$axios
.get(
"http://127.0.0.1:8000/api/all-appointments",
{
headers: {
Authorization: `Bearer ${bearerToken}`
}
}
)
.then(response => {
this.myAppointments = response.data;
console.log("Appointment", this.myAppointments);
});
} catch (error) {
console.log(error);
}
}
I get this error in the console.
Error in the Network.
and the Header gives me a 200 status code and I don't get why it's always been blocking.
I have allowed everything in the cors.php. I have set the proxy in my quasar framework to 10.30.154.253 (cause I'll be converting this to android cordova in quasar.) and I have allowed it in the backend.
'paths' => ['api/*', '/storage/images', 'sanctum/csrf-cookie','login','registration', 'myProfile', 'signout'],
'allowed_methods' => ['*'],
'allowed_origins' => ["http://127.0.0.1:8000", "http://10.30.154.253:8080"],
'allowed_origins_patterns' => ['*'],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
my Laravel controller for the query.
public function allAppointment()
{
$appointment = DB::table('appointments')
->select(
'appointments.id',
'appointments.name',
'appointments.branch',
'appointments.test',
'appointments.date',
'appointments.time',
'appointments.status',
'appointments.addressofHomeService',
'appointments.type',
'appointments.otherconcerns',
'appointments.remarks',
'appointments.file',
'appointments.fileExtension',
'appointments.created_at'
)
->join('users', 'users.id', '=', 'appointments.user_id')
->orderBy('appointments.created_at','desc')
// ->where('items.activeInactive', '=', 'Active')
->get();
return response()->json($appointment);
}
I also tried following the links here. https://www.positronx.io/how-to-enable-cors-in-laravel/?ref=morioh.com&utm_source=morioh.com and similar to this, still it hasn't been able to work.
How can I fix this?

axios sending null when uploading files to laravel api. Error Message: "Call to a member function store() on null"

I have a form with file upload. I am using vue, axios and laravel 7 at the moment.
My form is as given below:
<form v-on:submit.prevent="createTask" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" id="title" v-model="task.title" />
<label for="content">Content</label>
<textarea v-model="task.content" class="form-control" id="content" name="content" rows="4" ></textarea>
<button type="submit" class="btn btn-sm btn-primary
pull-right" style="margin:10px; padding:5 15 5 15; background-color:#4267b2">Save Task</button>
<span>
<button #click="removeImage" class="btn btn-sm btn-outline-danger" style="margin:10px; padding:5 15 5 15; ">Remove File</button>
</span>
<input type="file" id="image" name="image" />
</div>
</form>
Axios submission
createTask() {
console.log(document.getElementById('image').files[0])
axios({
headers: { 'Content-Type': 'multipart/form-data' },
method: 'post',
url: '/api/tasks',
data: {
task_id : this.task.id,
title : this.task.title,
content : this.task.content,
created_by : this.$userId,
image : document.getElementById('image').files[0],
}
})
.then(res => {
// check if the request is successful
this.$emit("task-created");
this.task = {}
})
.catch(function (error){
console.log(error)
});
}
My controller code
public function store(Request $request)
{
$task = $request->isMethod('put') ? Task::findOrFail($request->task_id) : New Task;
$task->id = $request->input('task_id');
$task->title = $request->input('title');
$task->content = $request->input('content');
$task->views = $request->input('views');
$task->created_by = $request->input('created_by');
$task->image = $request->image->store('images');
//$task->image = $request->file('image')->store('images');
if($task->save()) {
return new TaskResource($task);
}
}
The request payload
{task_id: "", title: "test", content: "test content", created_by: "1", image: {}}
We can see the image attribute is empty
The response error message
"Call to a member function store() on null"
The output of console.log(document.getElementById('image').files[0])
File {name: "test.jpg", lastModified: 1590920737890, lastModifiedDate: Sun May 31 2020 11:25:37 GMT+0100 (British Summer Time), webkitRelativePath: "", size: 436632, …}
lastModified: 1590920737890
lastModifiedDate: Sun May 31 2020 11:25:37 GMT+0100 (British Summer Time) {}
name: "test.jpg"
size: 436632
type: "image/jpeg"
webkitRelativePath: ""
proto: File
I solved this problem by changing the axios post request as follows. I used FormData to append and send data to server
createTask() {
let data = new FormData;
data.append('image', document.getElementById('image').files[0]);
data.append('task_id', this.task.id);
data.append('title', this.task.title);
data.append('content', this.task.content);
data.append('created_by', this.$userId);
axios({
headers: { 'Content-Type': 'multipart/form-data' },
method: 'post',
url: '/api/tasks',
data: data
})
.then(res => {
// check if the request is successful
this.$emit("task-created");
this.image = '';
this.task = {}
})
.catch(function (error){
console.log(error)
});
}
Assuming the image column has the right structure, you could try with somenthing like this:
<?php
public function store(Request $request)
{
$task = $request->isMethod('put') ? Task::findOrFail($request->task_id) : New Task;
$task->id = $request->input('task_id');
$task->title = $request->input('title');
$task->content = $request->input('content');
$task->views = $request->input('views');
$task->created_by = $request->input('created_by');
$task->image = $request->hasFile('images')
? $request->file('images')
: null;
if($task->save()) {
return new TaskResource($task);
}
}
laravel 5.4 upload image read here for more information

How to exchange data between Go Web-Server and Vue.js frontend? http-post : 404

I’m trying to understand how to exchange data between a very lean golang web-server and the vue.js frontend.
This is the server-gorillamux.go file :
package main
import (
"encoding/json"
"github.com/gorilla/mux"
"log"
"net/http"
)
const (
CONN_HOST = "192.168.1.7"
CONN_PORT = "3000"
)
type Puser struct {
first_name string `json:"first_name"`
last_name string `json:"last_name"`
company_name string `json:"company_name"`
email string `json:"email"`
tel string `json:"tel"`
}
type Pusers []Puser
var pusers []Puser
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{
"getPusers",
"GET",
"/pusers",
getPusers,
},
Route{
"addPuser",
"POST",
"/puser/add",
addPuser,
},
}
func getPusers(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(pusers)
}
func addPuser(w http.ResponseWriter, r *http.Request) {
puser := Puser{}
err := json.NewDecoder(r.Body).Decode(&puser)
if err != nil {
log.Print("error occured while decoding puser data :: ", err)
}
log.Printf("adding puser id :: % s with firstName ass :: %s and lastName as :: %s ",
puser.first_name, puser.last_name)
pusers = append(pusers, Puser{first_name: puser.first_name,
last_name: puser.last_name, company_name: puser.company_name,
email: puser.email, tel: puser.tel})
json.NewEncoder(w).Encode(pusers)
}
func AddRoutes(router *mux.Router) *mux.Router {
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
return router
}
func main() {
muxRouter := mux.NewRouter().StrictSlash(true)
router := AddRoutes(muxRouter)
router.PathPrefix("/").Handler(http.FileServer(http.Dir("../src/components
/auth/Forms.vue")))
//router.PathPrefix("/").Handler(http.FileServer(http.Dir("../public/")))
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
if err != nil {
log.Fatal("error starting http server :: ", err)
return
}
}
And this is /src/components/auth/Forms.vue file:
<template>
<div id="signupform">
<div class="signup-form">
<form #submit.prevent="onSubmit">
<div class="firstname">
<label for="firstname">First Name</label>
<input
type="string"
id="firstname"
v-model="firstname" placeholder="First Name">
</div>
<div class="lastname">
<label for="lastname">Last Name</label>
<input
type="string"
id="lastname"
v-model="lastname" placeholder="Last Name">
</div>
<div class="companyname">
<label for="companyname">Company Name</label>
<input
type="string"
id="companyname"
v-model="companyname" placeholder="Company Name">
</div>
<div class="input">
<label for="email">Mail</label>
<input
type="email"
id="email"
v-model="email" placeholder="e-mail">
</div>
<div class="input">
<label for="tel">Telephone Number</label>
<vue-tel-input v-model="tel"></vue-tel-input>
</div>
<div class="input inline">
<input type="checkbox" id="terms" v-model="terms">
<label for="terms">Accept Terms of Use</label>
</div>
<div class="submit">
<button type="submit">Submit</button>
</div>
</form>
</div>
</div>
</template>
<script>
//import axios from '../../axios-auth';
import Vue from 'vue';
import { VueTelInput } from 'vue-tel-input';
Vue.use(VueTelInput);
export default {
components: {
VueTelInput,
},
data () {
return {
firstname: '',
lastname: '',
companyname: '',
email: '',
tel: '',
terms: false
}
},
methods: {
onSubmit () {
const formData = {
first_name: this.firstname,
last_name: this.lastname,
company_name: this.lastname,
email: this.email,
tel: this.tel,
terms: this.terms
}
this.addPuser(formData);
},
addPuser (fdata) {
this.$http.post('/puser/add', {
fdata
//first_name:this.firstname,
//last_name:this.lastname,
//company_name:this.companyname,
//email:this.email,
//tel: this.tel
}).then(response => {
console.log(response);
}, error => {
console.error(error);
});
}
} // end of methods
}
</script>
<style scoped>
....
</style>
Executing the golang web-server:
(base) marco#pc01:~/webMatters/vueMatters/GraspGlobalChances/goServer$ go run server-
gorillamux.go
And compiling and running the vue.js frontend
DONE Compiled successfully in 1960ms 4:37:20 PM
App running at:
Local: http://localhost:8080
Network: http://ggc.world/
Update 1)
These are the last lines of /var/log/nginx/ggcworld-access.log corresponding to my last POST attempt :
2.36.119.16 - - [30/Apr/2020:16:01:41 +0200] "GET / HTTP/2.0" 200 694
"-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/81.0.4044.129 Safari/537.36"
2.36.119.16 - - [30/Apr/2020:16:01:41 +0200] "GET /js/app.js HTTP/2.0"
200 147353 "https://ggc.world/" "Mozilla/5.0 (X11; Linux x86_64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/$
2.36.119.16 - - [30/Apr/2020:16:01:42 +0200] "GET /js/chunk-vendors.js
HTTP/2.0" 200 4241853 "https://ggc.world/" "Mozilla/5.0 (X11; Linux
x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.$
2.36.119.16 - - [30/Apr/2020:16:01:42 +0200] "GET /sockjs-
node/info?t=1588255302671 HTTP/2.0" 200 79 "https://ggc.world/"
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/81$
2.36.119.16 - - [30/Apr/2020:16:03:50 +0200] "POST /puser/add
HTTP/2.0" 404 137 "https://ggc.world/" "Mozilla/5.0 (X11; Linux
x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129
Safari/53$
How to correctly exchange data between the golang web-server and the vue.js frontend?
Looking forward to your kind help.
Marco
Looks like your backend server is running at port 3000 whereas your frontend is running at post 8080. If yes, then please configure the proxy rules in your frontend application following document - API Proxying During Development

Vue html/text editor v-html not working when posted/put (added/edited)

So I'm scouring the internet and it seems as though I'm having the same problem as this issue here.
Basically to a T, I'm experiencing what that user experienced;
I've tried several HTML/Text editors (I'm sticking with Vue2-Editor now), and when I save a post it seems as though the v-html method doesn't do what it's supposed to or I am implementing something incorrectly.
HTML - Display Post
<div class="message" v-show="announcement.active" :class="{active: announcement.active}">
<div v-html="announcement.message"></div>
</div>
Displaying the post example
HTML - Edit Post
<div v-if="announcement.editing" class="update-inner-wrapper editing">
<header class="announcement-header">
<h3 class="date">{{ announcement.date | moment("MM/DD/YYYY") }}</h3>
<input class="title" v-model="announcement.title">
<div class="save-btn">
<button v-if="announcement.editing" #click="editUpdate(announcement, announcement.id)" class="edit">Save <svg class="icon"><use href="#approve"></use></svg></button>
</div>
</header>
<div class="message">
<vue-editor v-model="announcement.message"></vue-editor>
</div>
</div>
Editing the post example
HTML - Add Post
<section class="super-user-options" v-show="openPost">
<h2>Add a Post</h2>
<div class="form-wrapper">
<div class="super-user-form">
<div class="flex dt">
<div class="date-title">
<input placeholder="Enter a Title" v-model="newUpdate.title">
</div>
<mq-layout mq="desktop+">
<button type="submit" #click="addUpdate()" class="add-post-button">
Add Update
</button>
</mq-layout>
</div>
<div class="flex text">
<vue-editor v-model="newUpdate.message"></vue-editor>
<mq-layout mq="mobile">
<button type="submit" #click="addUpdate()" class="add-post-button">
Add Update
</button>
</mq-layout>
</div>
</div>
</div>
</section>
Adding a post example
JS - CUD Ops
async addUpdate(){
const user = await applicationUserManager.getUser()
let today = new Date().toJSON().slice(0,10).replace(/-/g,'-');
let newUpdateData = {
"date": today,
"message": marked(this.newUpdate.message, { sanitize: true }),
"title": this.newUpdate.title
}
this.OPENPOSTDIALOGUE();
this.UPDATE_KEY(this.componentKey += 1);
axios.post(this.announcementUrl, newUpdateData, { 'headers': { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + (user ? user.access_token : '') }})
.then(
axios.get(this.announcementUrl).then(response => {
this.announcements = response.data
})
)
},
//EDITUPDATE
async editUpdate(announcement, id){
const user = await applicationUserManager.getUser()
let newUpdateData = {
"id": announcement.id,
"date": announcement.date,
"message": marked(announcement.message, { sanitize: true }),
"title": announcement.title
}
this.UPDATE_KEY(this.componentKey += 1);
axios.put(this.announcementUrl + "/" + id, newUpdateData, { 'headers': { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + (user ? user.access_token : '') }})
axios.get(this.announcementUrl).then(response => {
this.announcements = response.data
})
},
//DELETE UPDATE
async deleteUpdate(announcement, id){
const user = await applicationUserManager.getUser()
axios.delete(this.announcementUrl + "/" + id, { 'headers': { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + (user ? user.access_token : '') }})
this.UPDATE_KEY(this.componentKey += 1);
axios.get(this.announcementUrl).then(response => {
this.announcements = response.data
})
},
What am I doing wrong?
The rich text editor is returning a html string which can be directly used in v-html.
So replace marked(announcement.message, { sanitize: true })
With: "message": announcement.message
Here's an example using CKeditor: https://jsfiddle.net/ellisdod/5g1cptjb/

how to post xml to the webservice and get a result using worklight

I am new to worklight and using http adapter for posting xml to webservices so that i can get the result.But I am not able to do that it is giving some error. My code is in adapter.js
function getStories(interest) {
path = getPath(interest);
var input = {
method : 'post',
returnedContentType : 'xml',
path : path
parameters : '<HOME><REQUEST><USERID>701692</USERID><SECURE_KEY>B6F86B1B11E9EAFC</SECURE_KEY><EMPLOYEE_ID>000000000000035B</REQUEST></HOME>'
};
return WL.Server.invokeHttp(input);
}
It is giving output like this
{ "errors": [
"Premature end of file.",
"Failed to parse the payload from backend (procedure: HttpRequest)" ], "info": [ ], "isSuccessful": false,
"responseHeaders": {
"Cache-Control": "private",
"Content-Length": "0",
"Date": "Mon, 15 Oct 2012 10:29:01 GMT",
"Server": "Microsoft-IIS/6.0",
"X-AspNet-Version": "2.0.50727",
"X-Powered-By": "ASP.NET" }, "statusCode": 200, "statusReason": "OK", "warnings": [ ] }
I want to have this code (given below ) to be implemented in worklight , how can i do that.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<BODY>
<form name="f1" id="fi" action="http://mydoman.aspx" method="post">
<input TYPE="hidden" name="xml" value="<HOME><REQUEST><USERID>701692</USERID><SECURE_KEY>B6F86B1B11E9EAFC17F5844EE9B16669</SECURE_KEY></REQUEST></HOME>"/>
<input type="submit" value="submit"/>
</form>
</BODY>
</HTML>
You are missing a step, you are trying to send an XML to your backend.
Please read Module 5.3 - Using HTTP Adapters with SOAP Services at: https://www.ibm.com/developerworks/mobile/worklight/getting-started/index.html
The answer to your question is:
var request = <HOME><REQUEST><USERID>701692</USERID><SECURE_KEY>B6F86B1B11E9EAFC</SECURE_KEY><EMPLOYEE_ID>000000000000035B</EMPLOYEE_ID></REQUEST></HOME>;
function getStories(interest) {
var input = {
method : 'post',
returnedContentType : 'xml',
path : '',
body : {
content: request.toString(),
contentType: 'text/xml; charset=utf-8'
}
};
return WL.Server.invokeHttp(input);
}
returnedContentType : 'xml' means that Worklight will try to parse the response it got from backend. Looking at the error message I can see "Content-Length": "0", which means that response body is empty, therefore it cannot be parsed to XML.
Try changing returnedContentType to 'plain'.
var request = '<HOME><REQUEST><USERID>701692</USERID><SECURE_KEY>B6F86B1B11E9EAFC</SECURE_KEY><EMPLOYEE_ID>000000000000035B</EMPLOYEE_ID></REQUEST></HOME>';
function getStories(interest) {
var input = {
method : 'post',
returnedContentType : 'xml',
path : '',
body : {
content: request,
contentType: 'text/xml; charset=utf-8'
}
};
return WL.Server.invokeHttp(input);
}