I'm using Vue.js 2 and the I18n plugin to create a multilanguage website. The required language file (in my example nl) is requested from an external url. Unfortunately I can't get it working.
function getLanguage() {
return Vue.http({
url: '/language/nl_NL.json',
method: 'get',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then(
response =>
response.json(),
() => {
/* Error */
}
);
}
Vue.config.lang = 'nl';
Vue.locale(Vue.config.lang, getLanguage());
console.log(getLanguage());
The /language/nl_NL.json file is a json file. The network connection is ok (returns 200) and the console.log() command is showing a Promise. But the translation across my website is not working. Vue.locale is not setting the file as a translation file and I can't figure out the problem.
Related
Hello Guys I have made an React Native Application using Expo and I have a question regarding a fetch call.
Lets say this is my fetch call:
const getMonthReport = async () => {
await fetch("http:/xxx/jasperserver/rest_v2/reportExecutions", {
method: "POST",
headers: {
"Accept": "application/xml",
"Content-Type": "application/xml"
},
body: { ... }
});
}
How can I pass my XML as the body of the request? It looks like this:
<reportExecutionRequest>
<reportUnitUri>/Test/MonthReport2</reportUnitUri>
<async>false</async>
<freshData>true</freshData>
<saveDataSnapshot>false</saveDataSnapshot>
<outputFormat>html</outputFormat>
<interactive>false</interactive>
<parameters>
<reportParameter name="allHrs">
<value>90:00</value>
</reportParameter>
<reportParameter name="holidayHrs">
<value>07:36</value>
</reportParameter>
<reportParameter name="illHrs">
<value>18:00</value>
</reportParameter>
</parameters>
</reportExecutionRequest>
I have written a lambda function in AWS which fetches the data from Dynamo DB and return in JSON format. It take a request input body in a format - {"Datestamp":"2021-01-11"} and return reports for this date.
I am calling this from a web page using java script but I am getting ``unable to marshal response``` error.
Javascript Code -
$.ajax({
type : "POST",
contentType : "application/json",
url : "https://mypoc-app.com/api/",
data:
{
"Datestamp" : "2021-02-15"
},
headers: {
'Authorization': 'Basic',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': 'DELETE, POST, GET, OPTIONS',
'Access-Control-Allow-Credentials' : true
//'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With',
},
dataType : "json",
success : function(data,status) {
console.log("Date format is " + data);
if (response != null)
{
drawTable(response.data);
}
},
error: function () {
console.log("Error");
}
});
Lambda function -
def lambda_handler(event, context):
try:
result = []
queryresponse = resultstable.scan()
for i in queryresponse['Items']:
result.append(i['reports'])
block=['{"type": "section","text": {"type": "mrkdwn","text": "*Found below reports using Datestamp provided*"}}']
for item in result:
print(event["body"])
body = json.loads(event["body"])
if item.find(body['Datestamp']) != -1:
itema='{"type": "section","text": {"type": "mrkdwn","text": "<https://%s/%s/%s/index.html|%s>"}}' % (URL,Prefix,item,item)
block.append(itema)
block=('[{}]'.format(', '.join(block)))
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': block,
"isBase64Encoded": False
}
except Exception as e:
print(e)
return(e)
Error Logs in Cloudwatch -
START RequestId: XXXXXXXXXXXXXXXXXXXX Version: $LATEST
Datestamp=2021-02-15
Expecting value: line 1 column 1 (char 0)
[ERROR] Runtime.MarshalError: Unable to marshal response: JSONDecodeError('Expecting value: line 1 column 1 (char 0)') is not JSON serializable
END XXXXXXXXXXXXXXXXXXXX
I believe it has something to do with the way I am passing date in the request or the way lambda is handling it because certainly from the cloud watch logs it doesn't look like it's in a JSON format.
Can someone please provide their expertise in this case as I have already scratched my head around it?
As you said it works fine from the console - i suspect your issue is trying to invoke it using AJAX. The better way would be to use the AWS SDK for JavaScript. Use the Lambda Client API to invoke the Lambda function from within a Script tag.
Here is the examples for JS API for Lambda:
https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/lambda
To invoke a Lambda function, you can call the invoke operation. See this Java example. Port this example to JS API.
https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaInvoke.java
To pass data, use the InvokeRequest object.
I would like to disable cache on getting a request in vue environment. I already tried this but it does not work.
api.js (file)
getCall: () => {
return performAsyncGet(apiConfig.getCall.url,
requestConfigJSON, _REQUEST_TOKENS.getCall, apiConfig.getCall.cache)
.then(
response => response.data
);
},
(apiConfig.js) (file)
getCall: {
url: `${servicePathPrefixOrDomain}/api/getCall`
cache: false
}
Does anybody know how to disable the cache, when making a get request in vue.js?
Thanks in advance!
To avoid caching you can make your url unique by appending timestamp as a querystring parameter like this:
getCall: {
url: `${servicePathPrefixOrDomain}/api/getCall?_t={new Date().getTime()}`
cache: false
}
In this way for every ajax call the url will be unique due to different timestamp and browser will not cache the response.
Is solved adding the next code in the header:
const requestConfigJSON = {
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
}
};
I have a form with multiple fileds, which one is a file input. I use axios to upload the file under a separate attribute:
axios.post(ENDPOINT,{
form: formData,
image: image
}, getAuthorizationHeader())
function getAuthorizationHeader() {
return {
headers: {
'Authorization': //...,
'Content-Type': undefined
}
};
}
formData is created like this:
let formData = new FormData();
formData.append('title', values.title);
formData.append('description', values.description);
formData.append('amount', values.amount);
And the image is:
Under the network tab of the Chrome Dev tool, When I look at the request, it looks like this:
As you can see in the screenshot, the file is empty? The CONTENT-TYPE is application/json which is not what I expected. I expected browser to detect the CONTENT-TYPE as multipart/form-data
What is wrong here?
First of all, image should be part of the formData:
formData.append('image', <stream-of-the-image>, 'test.png')
Secondly, formData should be the second parameter of axios.post:
axios.post(ENDPOINT, formData, getAuthorizationHeader())
Last but no least, you should merge formData.getHeaders():
function getAuthorizationHeader() {
return {
headers: Object.assign({
'Authorization': //...,
}, formData.getHeaders())
};
}
Sample code for your reference: https://github.com/tylerlong/ringcentral-js-concise/blob/master/test/fax.spec.js
I'm trying to use the Dropbox API to send files to a specific Dropbox folder via a web interface using Ajax.
Here is my code:
function UploadFile(token, callback) {
var fileName = $('input[type=file]')[0].files[0].name,
fileData = new FormData($('#file-upload')[0]),
dbxHeaderParams = {
'path': '/' + fileName,
'mode': { '.tag': 'add' },
'autorename': true
};
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/octet-stream',
'Dropbox-API-Arg': JSON.stringify(dbxHeaderParams)
},
data: fileData,
processData: false,
contentType: false,
success: function(result) {
console.log('NICE BRO');
callback();
},
error: function(error) {
console.error(error);
callback();
}
});
}
This code works: files are uploaded to my Dropbox folder and i can open them. They even have the right name and (almost) the right size. But the problem is that they are all corrupted because some lines are added during the process.
Here is an example: if I want to upload a .txt file containing this:
harder better faster stronger
Once uploaded on my Dropbox, it will looks like this:
-----------------------------2308927457834
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: text/plain
harder better faster stronger
-----------------------------2308927457834--
I assume this is why I can't open files like images. I've tried several solutions but none of them can solve this. What am I doing wrong ? Thanks !
Seeing the relevant pieces of the HTML would be useful, but it looks like the issue is that you're supplying a FormData object to the upload call, as opposed to the File.
Try replacing this line:
fileData = new FormData($('#file-upload')[0]),
with this:
fileData = $('input[type=file]')[0].files[0],