I'm uploading multiple files separately using axios.
This is the request(all the following code is inside an async function):
const proms = files.map(file => {
let formData = new FormData();
formData.append("file", file);
return axios.post(`/upload/${userId}`, formData)
});
proms will be an array of promises so I proceed to Promise.all it:
const res = await Promise.all(proms)
If I do console.log(res) it shows a successfull response from server as you can see here:
Array(3) [ {…}, {…}, {…} ]
0: Object { data: {…}, status: 200, statusText: "OK", … }
config: Object { timeout: 0, xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", … }
data: Object { fieldname: "file", originalname: "612_photo.jpg", encoding: "7bit", … }
destination: ************************
encoding: "7bit"
fieldname: "file"
filename: "/1648309550808-586868206.jpeg"
mimetype: "image/jpeg"
originalname: "612_photo.jpg"
path: ************************
size: 43267
<prototype>: Object { … }
headers: Object { "content-length": "395", "content-type": "application/json; charset=utf-8" }
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
status: 200
statusText: "OK"
<prototype>: Object { … }
1: Object { data: {…}, status: 200, statusText: "OK", … }
2: Object { data: {…}, status: 200, statusText: "OK", … }
length: 3
<prototype>: Array []
But then when I do console.log(res.data) it is undefined. What is happening here?
your response(res) is An array so you cant access res.data ,try :
res.forEach(item=>{console.log(item.data)})
Related
Trying to send an image through GupShup. I'm using their sandbox. My backend is node.js with feathersjs.
But it's returning me this error:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
readable: true,
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: true,
_transformState: [Object],
[Symbol(kCapture)]: false
},
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
url: 'https://api.gupshup.io/sm/api/v1/msg',
status: 400,
statusText: 'Bad Request',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
}
}
This is the code to send the image
const form = new URLSearchParams();
form.append('channel', 'whatsapp');
form.append('destination', destination);
form.append('source', app.get('GUPSHUP_NUMBER'));
form.append('message.payload', JSON.stringify(message));
form.append('src.name', 'OneAccess');
console.log(form);
try {
const res = await fetch('https://api.gupshup.io/sm/api/v1/msg', {
method: 'POST',
body: form,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
apikey: app.get('GUPSHUP_API'),
},
});
console.log('result message', res);
} catch (err) {
console.log('errro sending msg', err);
}
This is the message that I'm trying to send
message: {
type: 'image',
originalUrl:
'https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg',
previewUrl:
'https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg',
caption: 'Sample image',
},
Can anyone help me?
Change message.payload to message. You can check the correct signature at https://www.gupshup.io/developer/docs/bot-platform/guide/whatsapp-api-documentation#SendImage
I'm sending request response to app class via redux.
And I receive it in props as I can console.log(this.props.data);
But I get this nested array full of objects
I've tried
console.log(this.props.data[0].PromiseValue);
which results in undefined
[Promise]
0: Promise
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
headers: {pragma: "no-cache", content-type: "application/json; charset=utf-8", cache-control: "public, max-age=14400", expires: "Mon, 01 Apr 2019 22:25:19 GMT"}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: ""
Have you tried to bind to the "then" event of the promise? Something like this:
this.props.data[0].then(value => {
console.log(value);
});
We got a ReactJS frontend delivered for our school project. We have to make a Laravel backend for it. I'm using an API to fetch the dashboard layout from the database. The current frontend makes use of this variable:
const originalLayouts = getFromLS("layouts") || [];
To set the state from the local storage with this function:
function getFromLS(key) {
let ls = {};
if (global.localStorage) {
try {
ls = JSON.parse(global.localStorage.getItem("rgl-8")) || {};
} catch (e) {
/*Ignore*/
}
}
return ls[key];
}
Where the states are set:
this.state = {
items: originalLayouts.map(function(i, key, list) {
return {
i: originalLayouts[key].i,
x: originalLayouts[key].x,
y: originalLayouts[key].y,
w: originalLayouts[key].w,
h: originalLayouts[key].h,
widget: originalLayouts[key].widget,
minW: originalLayouts[key].minW,
minH: originalLayouts[key].minH,
maxH: originalLayouts[key].maxH
};
}),
selectedOption: '',
newCounter: originalLayouts.length
};
To fetch the data from the database and put the data into the items state I made this function:
loadData = () => {
let dashboardId = 1;
return axios
.get('api/dashboards/' + dashboardId)
.then(result => {
console.log(result);
this.setState({
originalLayouts: result.data,
selectedOption: '',
newCounter: originalLayouts.length
});
console.log(result.data);
})
.catch(error => {
console.error('error: ', error);
})
};
And I call this function in componentDidMount:
componentDidMount() {
this.loadData();
}
When I console log result it shows me this:
data: Array(2), status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data: (2) [{…}, {…}]
headers: {date: "Tue, 23 Oct 2018 08:18:41 +0000, Tue, 23 Oct 2018 08:18:41 GMT", host: "127.0.0.1:8000", x-powered-by: "PHP/7.2.3", x-ratelimit-remaining: "58", content-type: "application/json", …}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: "OK"
__proto__: Object
And when I console log result.data I get:
(2) [{…}, {…}]
0: {id: 1, dashboardId: 1, w: 2, h: 5, x: 0, …}
1: {id: 2, dashboardId: 1, w: 2, h: 1, x: 0, …}
length: 2
__proto__: Array(0)
Why is originalLayouts not set with the data from the arrays? Is this because I also have a dashboardId and id in my arrays? I also thought it could be something with setting the states because it makes use of the originalLayouts veriable. Or am I still missing something in my function? I'm not very experienced with React so any help is useful.
Update:
I changed:
this.setState({
originalLayouts: result.data,
selectedOption: '',
newCounter: originalLayouts.length
});
to:
this.setState({
items: result.data,
selectedOption: '',
newCounter: originalLayouts.length
});
This gives me this error:
Uncaught Error: ReactGridLayout: ReactGridLayout.children[0].static must be a boolean!
So that probably means I'm not setting the properties properly now.
Update 2:
In my database the properties moved and static were saved as 0 instead of false. So I changed those properties to false but I still got the same error:
ReactGridLayout: ReactGridLayout.children[0].static must be a boolean!
In your loadData(), you are setting the state of "originalLayouts" but your key in your initial state is "items". Have you tried to do this ?
this.setState({
items: result.data, // Here put items instead of originalLayouts
selectedOption: '',
newCounter: originalLayouts.length
});
Then you can call this.state.items to get your result.data
In my react-native application on the login screen I'm working on providing the user with nice error messaging after entering in the incorrect username / password combination. To interact with the API I'm using the library Axios. However when I get an error in the catch statement, I get this ugly error message saying that I have an "unhandled promise rejection" and I cannot do things such as set the components state or navigate to a new page.
I can't see what I'm doing wrong, it looks exactly like examples I've seen in the docs.
In my form submission function I have:
axios.post('http://192.168.1.11:1337/login', {
email: this.state.username,
password: this.state.password
}).then(function (response) {
// This stuff all seems to work great
console.log("The response we got: ", response);
if (response.status == 200) {
console.log("Status code equals 200");
Actions.homepage();
}
}).catch(function (err) {
// Run into big problems when I get an error
console.log("Got an error logging in, here's the message: ", err);
});
Can anyone see what I'm doing wrong here?
P.S. Here is the error message I'm getting back from the server, which get's logged from that console.log("Got an error logging in, here's the message: ", err);:
"Got an error logging in, here's the message:"
{ [Error: Request failed with status code 401]
config:
{ transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
headers:
{ Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8' },
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
method: 'post',
url: 'http://192.168.1.11:1337/login',
data: '{"email":"zach#homies.io","password":"dddddd"}' },
response:
{ data: { message: 'Invalid password', user: false },
status: 401,
statusText: undefined,
headers:
{ map:
{ connection: [ 'keep-alive' ],
date: [ 'Thu, 31 Aug 2017 23:30:21 GMT' ],
'x-powered-by': [ 'Sails <sailsjs.org>' ],
vary: [ 'X-HTTP-Method-Override' ],
'content-length': [ '52' ],
'access-control-allow-credentials': [ '' ],
'access-control-allow-origin': [ '' ],
etag: [ 'W/"34-Ymi4isRxuJ6jE1EIS+AQag"' ],
'access-control-allow-methods': [ '' ],
'access-control-allow-headers': [ '' ],
'access-control-expose-headers': [ '' ],
'content-type': [ 'application/json; charset=utf-8' ] } },
config:
{ transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
headers:
{ Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8' },
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
method: 'post',
url: 'http://192.168.1.11:1337/login',
data: '{"email":"zach#homies.io","password":"dddddd"}' },
request:
{ url: 'http://192.168.1.11:1337/login',
credentials: 'omit',
headers:
{ map:
{ accept: [ 'application/json, text/plain, */*' ],
'content-type': [ 'application/json;charset=utf-8' ] } },
method: 'POST',
mode: null,
referrer: null,
_bodyInit: '{"email":"zach#homies.io","password":"dddddd"}',
_bodyText: '{"email":"zach#homies.io","password":"dddddd"}',
bodyUsed: true } } }
Here is a screenshot of what it looks like on the Android emulator (emulating a Samsung Galaxy S7):
There is nothing wrong in this snippet.
You send a request.
You get a 401 - unauthorized response.
Catch receives the error and logs it.
The interesting part is why you get that unhandled promise rejection error.
But this is thrown somewhere else. So you need to provide more of the code.
Edit:
Perhaps you just have to return your axios promise to the calling function?
I have same problem and I use Firebase for database
I resolve this problem
put database on realtime instead of cloud Firestore like the picture
I hope this worked for you
I'm writing a simple Chrome extension, the behavior is needed to detect if device is connect to the Internet. I'm currently trying to connect to ping service for checking network status and it is not efficient. Is there any event to which I can listen from Chrome JavaScript API?
There is no specific event in the Chrome extension APIs intended to be used for this purpose.
In "How to detect online/offline event cross-browser?" it is suggested that you can use window.navigator.onLine and the events (from MDN):
window.addEventListener('offline', function(e) { console.log('offline'); });
window.addEventListener('online', function(e) { console.log('online'); });
However, my testing on Windows 10 x64 using Chrome Version 56.0.2924.87 (64-bit) indicated that none of those are valid. When the network cable was physically disconnected, the events did not fire in either the background script, nor a content script In addition, the value of window.navigator.onLine remained true in both. There was a similar lack of activity when the network cable was plugged back in.
Potential events to which you might listen
However, when the network cable was disconnected a webRequest was fired. Specifically the following events:
webRequest.onBeforeRequest -> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestId: "10787", tabId: -1, timeStamp: 1487550094371.293, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onBeforeSendHeaders-> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestHeaders: Array[4], requestId: "10787", tabId: -1, timeStamp: 1487550094371.3901, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onSendHeaders -> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestHeaders: Array[4], requestId: "10787", tabId: -1, timeStamp: 1487550094371.437, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onErrorOccurred -> arg[0]= Object { error: "net::ERR_NAME_NOT_RESOLVED", frameId: -1, fromCache: false, method: "GET", parentFrameId: -1, requestId: "10787", tabId: -1, timeStamp: 1487550096326.291, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
When the cable was reconnected, the following sequence of webRequests were fired:
webRequest.onBeforeRequest -> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestId: "10938", tabId: -1, timeStamp: 1487550516485.3562, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onBeforeSendHeaders-> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestHeaders: Array[4], requestId: "10938", tabId: -1, timeStamp: 1487550516485.523, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onSendHeaders -> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestHeaders: Array[4], requestId: "10938", tabId: -1, timeStamp: 1487550516485.565, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onHeadersReceived -> arg[0]= Object { frameId: -1, method: "GET", parentFrameId: -1, requestId: "10938", responseHeaders: Array[12], statusCode: 200, statusLine: "HTTP/1.1 200"tabId: -1, timeStamp: 1487550518279.5378, type: "other", url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onResponseStarted -> arg[0]= Object { frameId: -1, fromCache: false, ip: "216.58.193.68", method: "GET", parentFrameId: -1, requestId: "10938", responseHeaders: Array[12], statusCode: 200, statusLine: "HTTP/1.1 200", tabId: -1, timeStamp: 1487550518279.653type: "other"url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
webRequest.onCompleted -> arg[0]= Object { frameId: -1, fromCache: false, ip: "216.58.193.68", method: "GET", parentFrameId: -1, requestId: "10938", responseHeaders: Array[12], statusCode: 200, statusLine: "HTTP/1.1 200", tabId: -1, timeStamp: 1487550518279.754type: "other"url: "https://www.google.com/searchdomaincheck?format=domain&type=chrome", __proto__: Object }
So, it appears that good candidates for events to watch are webRequest.onErrorOccurred for going offline and webRequest.onCompleted for going online, both with the URL: https://www.google.com/searchdomaincheck?format=domain&type=chrome.
This would need further testing. It was only tested on the configuration mentioned above.
On my MacBook navigator.onLine works as expected if I turn wifi on and off.
console.log("Is the browser online? "+ navigator.onLine);
With and without wifi enabled...