How to get response from other file request response in Laravue - laravel

I'm trying to get the response from File2.vue and pass back to File1.vue. I'm using VueJS v1.0.28, How to get response from other file request response?
File1.vue
File2.updateNotice(this,{'id':id}).then((response) => {
console.log("response from File2 :",response)
});
File2.vue
updateNotice(context,params) {
let url = staff_service.STAFF_NOTICES_READ_RESOURCE;
Vue.http.post(
url,
params
).then(response => {
return response;
})
}
Error response from File1:
Cannot read property 'then' of undefined

This is now solved, added a
return
before
Vue.http.post(
in File2.vue
File1.vue
File2.updateNotice(this,{'id':id}).then((response) => {
console.log("response from File2 :",response)
});
File2.vue
updateNotice(context,params) {
let url = staff_service.STAFF_NOTICES_READ_RESOURCE;
return Vue.http.post(
url,
params
).then(response => {
return response;
})
}

Related

FormData not being read by laravel on backend

This qn is related to vue and alravel, I try to make and api request on vue with const response = await http.put("api/v1/vehicles/" + vehicleId,formData);. I see the data going on payload, But when i DO dd($request->all()) It shows empty
async update(vehicleId, data) {
try {
let formData = new FormData();
(data.files ?? []).forEach((file, key) => {
formData.append("files[]", file);
});
Object.entries(data).forEach(([key, value]) => {
if (key !== "files" && value !== null) formData.append(key, value);
});
const response = await http.put(
"api/v1/vehicles/" + vehicleId,
formData
);
return Promise.resolve(response.formData);
} catch (err) {
return Promise.reject(err);
}
},
When I hit url with const response = await http.put("api/v1/vehicles/" + vehicleId,data); It shows on $request->all(). I need to add formData to attach the fiels. Is it because put request doesnot read formData??
I saw a method spoofing and I did this
let vehicle_data = { _method: "PUT", form: formData };
const response = await http.post(
"api/v1/vehicles/" + vehicleId,
vehicle_data
);
BUt it gives null on form?
PUT and PATCH request types require adding a _method property in payload and using .post instead .put
Said that, you should do this:
async update(vehicleId, data) {
try {
let formData = new FormData();
(data.files ?? []).forEach((file, key) => {
formData.append("files[]", file);
});
Object.entries(data).forEach(([key, value]) => {
if (key !== "files" && value !== null) formData.append(key, value);
});
formData.append("_method", "PUT")
const response = await http.post(
"api/v1/vehicles/" + vehicleId,
formData
);
return Promise.resolve(response.formData);
} catch (err) {
return Promise.reject(err);
}
},
Please note that I've changed request to http.post() and added formData.append("_method", "PUT")
Your API will recognize it as a PUT request and also grab payload correctly.
The same should be done for PATCH requests.

using https.get instead of got causes a 308

this is a difficult question to ask because I am mystified, but let's see…
I am comparing Got with https.get, and have the following, bare simple code that works. Both Got and https.get return exactly the same result.
But when I use exactly the same code in my Fastify application, Got works as expected but https.get results in a 308.
Is there some way I can debug this code to see what is being sent out by https.get that is causing the remote server to respond with a 308 instead of 200?
import got from 'got';
import https from 'https';
const withGot = async (uri) => {
try {
const json = JSON.parse((await got(uri)).body);
console.log(json);
}
catch (error) {
console.error(error);
}
}
const withHttps = async (uri) => {
try {
const json = await getRequest(uri);
console.log(json);
}
catch (error) {
console.error(error);
}
}
const getRequest = async (uri) => {
return new Promise((resolve) => {
https.get(uri, (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
/**
* Any 2xx status code signals a successful response but
* here we're only checking for 200.
**/
if (statusCode !== 200) {
error = new Error(`ERROR\n${'-'.repeat(50)}\nRequest Failed.\nURI: ${uri}\nStatus Code: ${statusCode}`);
}
else if (!/^application\/json/.test(contentType)) {
error = new Error(`Invalid content-type.\nExpected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
/**
* Consume response data to free up memory
**/
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
resolve(parsedData);
}
catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
});
}
const uri = 'https://zenodo.org/api/records/?q=phylogeny';
withGot(uri);
withHttps(uri);
I figured out the reason for the problem (and the solution)… seems like when I use https.get, I still have to pass the options with a port 443 (the default port for https), otherwise, https seems to knock on port 80 and then gets redirected to port 443 which results in the server sending back html which causes the JSON parser to croak. If I pass an options object like below, then it works. But, it is still weird that the standalone script works fine without the options, so I continue to be mystified even though I have found a solution.
const options = {
hostname: 'zenodo.org',
port: 443,
path: `/api/records/?${qs}`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};

Cypress not waiting for Before block to complete

I am trying to achieve the following functionality
Before Block : Call the Cy.visit("/login") and call a Function which will trigger a REST API and process the REST API response and set the local storage.
Only after the local storage is set click on "My Account" Link
Here is the source Code I am trying.
import * as subscriberHelpers from '../../../helpers/subscriberHelpers';
import * as localStorage from '../../../helpers/localStorage';
describe('testCode', () => {
before((done) => {
cy.visit('/login', {
timeout: 10000,
onLoad: () => {
localStorage.write("CD-Environment", Cypress.env('defaultEnvironment'));
localStorage.write("CD-Language", "en-US");
localStorage.write("CD-SystemId", "85788485-e411-48a9-b478-610c1285dc1a");
}
})
subscriberHelpers.createSubscriber().then(()=>{
done();
})
})
it('sClick on my account link', () => {
cy.get('.c-header-listItem > .c-link').contains("My Account").click();
})
})
Here is the code to createSubscriber function
export function createSubscriber() {
let URL = `SOME URL`;
let body = {
Some Body
}
return new Promise((resolve, reject) => {
request.subscriberServiceRequest(URL, body).then((response) => {
if (response.status === 200 && ("SessionId" in response.body)) {
localStorage.write("CD-SessionId", response.body.SessionId);
localStorage.write("CD-SubscriberId", response.body.Subscriber.Id);
resolve();
}
else if (response.status === 200 && ("Fault" in response.body)) {
reject(response.body.Fault.Message);
}
})
})
}
Here is the code to subscriber Service request function
export function subscriberServiceRequest(url, body, headers = null) {
let defaultHeaders = { "CD-SystemId": "85788485-e411-48a9-b478-610c1285dc1a" }
if (headers != null) {
defaultHeaders = addHeaders(defaultHeaders, headers);
}
return new Cypress.Promise((resolve, reject) => {
cy.request({
url: url,
method: 'POST',
body: body,
headers: defaultHeaders
}).then((response) => {
resolve(response);
});
})
}
When I try Executing the code I am getting following error in cypress
But the element existing in the UI
Questions:
Why I am getting the error
How to call more than one async functions
in before block
How to tell cypress to wait till the functions on
before block get processed meaning not only wait till receiving the
response but wait till the response got processed in the THEN block
To answer your first question:
Why I am getting the error
.contains() specifically searches for elements within but not including the tag it is called on. In other words, someElement.contains("My Account") will not match someElement.
What you should have instead is this:
cy.get('.c-header-listItem').contains("My Account").click();
Or simply:
cy.contains("My Account").click();

How can I get the actual error from fetch api

I am making a fetch api call but in case of a 500 error the following middleware kicks in and sends back a json object in response body.
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
if (context.Response.HasStarted)
{
throw;
}
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
var json = JToken.FromObject(ex);
await context.Response.WriteAsync(json.ToString());
}
});
On the client side I have the following code
return fetch(url, content)
.then(function(res) {
if (!res.ok) {
console.log(res, res.json())
throw Error(res.statusText);
}
return res;
})
.then(res => res.json())
.catch(e => console.log('Error fetching accounts:', e))
I am not able to access the json with error information. How can I do it ?
Working code after following the correct answer
return fetch(url, content)
.then(function(response) {
if (!response.ok) {
return response.json()
.then(function(obj) {
throw Error(obj.ErrorMessage)
})
}
else {
return response.json()
.then(json => {
/*further processing */
})
}
}).catch(/* work with the error */)
The json function of the Response object returns a Promise, not the actual parsed value.
res.json()
.then(function(object) {
// Here you have the parsed JSON object.
console.log(object);
});

Winjs get request failing to return data

I encountered a strange problem. In my app I have the following code
WinJS.xhr({
url: 'http://bdzservice.apphb.com/api/Route?fromStation=София&toStation=Варна&date=30/08/2013&startTime=00:00&endTime=24:00'
}).then(function (success)
{
console.log(success);
},
function (error)
{
console.log(error);
}
);
The problem is I get an empty response text (with status 200). The Url I provided returns data through the browser and other rest clients, but in the app I get no data. Where might be the problem?
You need to encode query string parameters via encodeURIComponent (browser does this for you automatically when pasting url).
Following code will do the trick:
function serialize (obj) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
};
var request = {
fromStation: 'София',
toStation: 'Варна',
date: '30/08/2013',
startTime: '00:00',
endTime: '24:00'
};
WinJS.xhr({
url: 'http://bdzservice.apphb.com/api/Route?' + serialize(request)
}).then(function(success) {
console.log(success);
},
function(error) {
console.log(error);
}
);

Resources