I am using request() in a for loop to post data to a server. Will it fail to post all data. Is there any limit of data posting rate in electron js. Here, request() mathod is of request npm module.
const request = require('request);
sendData(reqBody){
request({
url: config.dataDumpUrl,
method: "POST",
json: true, // <--Very important!!!
body: reqBody
}, async (error, response, body) =>{
if (error) {
console.log('error in data post');
}
})
}
then I call the sendData mathod in a for loop like below:
for(let i=0;i<1000;i++){
sendData(reqBody);
}
the 1000 request is done asynchronously in for loop. Will it be blocked by any maximum simultaneous request limit?.
Related
I was testing get and post requests in jsfiddle to better understand cors and csrf.
const data = { name: 'example', password: 'password'};
fetch('http://localhost:3001', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hi')
})
app.post('/', (req, res) => {
console.log('received')
res.send('Received')
})
app.listen(3001, () => {
console.log('Listening on port', 3001)
})
Is it normal that the first preflight request fails when doing a post request?
Also, shouldn't the successful preflight request happen before the post request? (On the server side, the code handling the post request isn't executed (nothing logged in console), which means that the browser cancelled the post request. How would the browser know not to follow through with the post request without waiting for the preflight request to complete first?)
Update:
Tried it using a simple html page instead of jsfiddle and the preflight request doesn't fail, but it still happens after the fetch request
Edit:
Only one options request is received on the server
// debugging middleware, should be first router handler of any kind
let requestCntr = 0
app.use((req, res, next) => {
let thisRequest = requestCntr++
console.log(
`${thisRequest}: ${req.method}, ${req.originalUrl}, `,
req.headers
)
// watch for end of theresponse
res.on('close', () => {
console.log(
`${thisRequest}: close response, res.statusCode = ${res.statusCode}, outbound headers: `,
res.getHeaders()
)
})
next()
})
Edit 2: from console
For a get request, no network error is shown in the Network tab, but the same error appears in the console except with a status code
It seems that Chrome simply displays the preflight request with a network error in the Network tab if it's related to csrf. Since opaque GET requests are fine, this doesn't happen for GET requests. So in the case of a post request, even if "preflight" shows up twice, it's the same preflight request.
I am trying to use the composition api on my Vue app, and I need to do a post request to my backend api. I am trying to make use of the "useAxios" utility from vueuse, but I can't figure out how to pass data into a post request. It isn't shown properly in the docs...
I want to convert the following axios request into one that uses "useAxios".
await axios.put(`/blog/posts/${route.params.postID}/`, post.value)
.then(() => notification = "Post Created!")
.catch(() => {
error = "Failed to create post"
});
I tried setting the value of the data field, but that didn't work...
const {data, execute, isFinished} = useAxios(axios)
data.value = post
await execute(`/admin/blog/posts/${route.params.postID}/`, {method: "PUT"})
I also tried passing the post object into the execute method as a parameter, but my ide complained.
Thanks in advance!
Set up your pending request ahead of time:
const { data, execute, isFinished } =
useAxios(`/admin/blog/posts/${route.params.postID}/`,
{ method: "PUT" },
{ immediate:false });
Then in the future you can call it by passing the data as follows:
const requestBody = { /* your data */ };
await execute({ data: requestBody });
As axios GitHub page states, default response of axios request is:
{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the headers that the server responded with
// All header names are lower cased
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
}
Problem:
My API response schema is:
{
success: true,
message: '',
data: {}
}
So every time I make a request, I have to handle the response like:
(...).then((res) => res.data.data);
How can I change the response schema of axios to avoid doing .data.data every time?
You can use a response interceptor to change the value of the promise:
axios.interceptors.response.use(function (response) {
return response.data.data
})
You'd just do this once and then it would apply to all requests made via the default axios instance. A similar approach can be taken if you're creating your own axios instances using axios.create.
You may also need to consider how to handle error cases but the approach is much the same.
Documentation: https://github.com/axios/axios#interceptors
Update:
If you need access to success, message and data you would just need this instead:
axios.interceptors.response.use(function (response) {
return response.data
})
Destructuring would potentially be useful when you write the then handler:
(...).then(({ data, success, message }) => {
});
Problem
Cypress returns timeout while the GET request is complete.
Description
GET request using Cypress.io
I should receive large (over 15Mb) response body from the API, but i have this:
"CypressError: cy.request() timed out waiting 300000ms for a response from your server."
Increasing the "responseTimeout" didn't help...
I also checked the same request in POSTMAN and it ending up with success, always in maximum 50 seconds.
Logs shows us that the request which is timed out in cypress is actually finished, so I suppose this is the cypress issue
EDIT: there are examples of my code, I already tried to do something with "async" but timeouts are still occurring. Usually every second test is failing with timeout but it is not the rule.
commands.js:
Cypress.Commands.add('getRequestLimit', (token, limit) => {
cy.request({
failOnStatusCode: false,
url: '/endpoint',
headers: {
'Authorization': 'Bearer '+token
},
qs: {
'limit' : limit,
}
})
});
cypress.json:
{
"baseUrl": "url",
"chromeWebSecurity": false,
"video": false,
"numTestsKeptInMemory": 0,
"responseTimeout": 500000,
"pageLoadTimeout": 500000
}
test file:
it('Check query param "limit"', () => {
const limit = 3;
cy.getRequestLimit(token, limit)
.then((response) => {
expect(response.status).to.eq(200);
});
});
it('Check query param "offset"', () => {
const offset = 3;
cy.getRequestOffset(token, offset)
.then((response) => {
expect(response.status).to.eq(200);
});
});
This is the cypress issue, https://github.com/cypress-io/cypress/issues/6385
right now it is working fine in version 3.3.1
Try to use async/await for your api calls this can be a solution for your problem.
Doc here: async function MDN web docs
Hard to say for sure without looking on your code.
I'm facing an issue while using react native fetch api. many times request got failure . I have a high speed connection. but many times it got failed.
that issue is happening In android,ios both.
const shoppingApi = 'myserverlink';
async function Sendshoppinapi(data) {
try {
let response = await fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
});
let responseJson = await response.json();
return responseJson;
}
catch (error) {
Alert.alert(error.toString())
}
}
export {Sendshoppinapi};
data that I sending server as post request
add_to_wishlist = (item,index) => {
{
let data = new FormData();
data.append('methodName', 'add_to_wishlist');
data.append('user_id', global.userid)
data.append('item_id', this.props.navigation.state.params.itemid.toString())
Sendshoppinapi(data).then((responseJson)=>{
console.warn(responseJson);
if(responseJson.responseCode == '200'){
this.setState({fav:false})
Alert.alert('SHOPPING','Item added to wishlist successfully.',[{text: 'OK',},],{ cancelable: false })
}
else{
this.setState({fav:false})
Alert.alert('SHOPPING','Item already .',[{text: 'OK',},],{ cancelable: false })
}
})}
}
Error that when request got failed
I've quoted an answer I used for another post - however I have added await.
You can check the status of the call, to determine perhaps why the network call failed. Try using fetch's ok to check whether the response was valid, for example:
.then(function(response) {
if (!response.ok) {
//throw error
} else {
//valid response
}
})
Using await:
let response = await fetch(url)
if (response.ok) return await response.json()
You can also access the response's status like:
response.status;
or also, statusText such as:
response.statusText;
checkout the below:
https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText
https://developer.mozilla.org/en-US/docs/Web/API/Response/status
https://www.tjvantoll.com/2015/09/13/fetch-and-errors/
Use then() function with promises. (Requested code snippet)
fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
})
.then((resp) => {
return resp.json()
})
.then((resp) => {
//resp contains your json data
});
You also can make your function returns a Promise, and use it with then():
function sendShoppingApi(data) {
return new Promise((resolve, reject) => {
fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
})
.then((resp) => {
return resp.json();
})
.then((resp) => {
resolve(resp);
/*
you should also check if data is valid, if something went wrong
you can reject the promise:
if(!dataOK)
reject("error message");
*/
});
});
}
So now you can do something like this:
sendShoppingApi(data)
.then((resp) => {
//do stuff with your data
})
.catch((err) => {
//handle error
});
UPDATE
could be a duplicate of this: React Native fetch() Network Request Failed
For the case when you are running the app on the android device, the API is on a computer and both of them are on the same network I have added some possible things to check. I haven't detailed specific solutions since there are many answers on each topic.
Do a quick check with ngrok https://ngrok.com/ on the free plan to see if that works. If yes:
Make sure the API is accessible by trying to access it on the device browser (most important is to check if you allow the port at inbound rules, firewall).
If you are using HTTPS, you might get an error if your react native env is not properly configured to accept not trusted certificates, assuming you are using a non trusted one. Do a check without HTTPS, only with HTTP, to see if it's the case. https://github.com/facebook/react-native/issues/20488