React Axios post request is getting timed out after 4 minutes - javascript

Building React app. Using Axios to upload file. Simple post request with FormData and multipart/form-data header is getting time out after 4 minutes in Chrome and 2 minutes in Safari.
As backend I'm using Django.
In dev environment I'm using proxy parameter in package.json to connect to backend via localhost.
As production environment I'm building static files via npm run build command and Django is serving them directly without any proxy like nginx.
The issue is present in local/dev and production environment.
Need help as I'm getting insane here, as any work around is not working.
Thanks in advance.
loadData = () => {
let formData = new FormData();
formData.append('file', this.state.file);
let path = `/path`
this.setState({loading: true});
axios(path, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
data: formData
})

Ok!
It was quite a while since post but I figured it out. Apparently it was timeout configured on Gunicorn it was exactly 120 sec. Why it was longer on Chrome? No idea but this difference between Chrome and rest of the browser threw me in the wrong direction.
So yea, fixed.

Related

How can I split my Vue js project into development and test?

I want to divide my vuejs frontend project into two parts as development and test. In the development part, I want to work in my local and request the example:8010 urline, and in the test part, I want to send a request to the example:80 address. How can I do this, I did a source search but couldn't find anything.
Example of a request I wrote:
var formData = new FormData();
formData.append('file', this.image[0]);
await axios
.post('example', formData, {
headers: {
Authorization: `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6fdsaeqImNoZ3VuYXkzQGdtYWlsLmNvbqSIsImlkIjoxLCJ0eXBlIjoxLCJpYXQiOjE2NDU0NDUxMjR9.Kg8NcFiAKtBHxkQsRwl2pO6svp7SDQSQw13SJ4xe1vc`,
},
})
.then((response) => {
console.log(response.data.id);
})
.catch((error) => {
console.log(error);
});
Serkan
You can use .env files for your environments. You can add dotenv package your project, or you can give parameters inside of your scripts part of you package.json
here you can follow this page to use your env variables inside vue app. Keep in mind you must start VUE_APP for your variables:
VUE_APP_BASE_API = 'yourapplink/api'
You should create 2 .env files 1 for your local development other for your production and you can add as much as you like.
You can create .env.development and put your variables in it then start your vue app with:
vue-cli-service build --mode development
And you should see app using your .env.development file.

ServerRuntimeConfig is empty

I am working on my nextjs project under docker, and when using getStaticProps my backend api is not available(which is also under docker). So I connected frontend to backend via networks and if i hardcode api for ssr request it works. But when i try to utilize serverRuntimeConfig and publicRuntimeConfig so i could switch between them depending on where code is being ran I get {} for serverRuntimeConfig. However publicRuntimeConfig is fine and i can access api from it.
My next.config.js is:
module.exports = {
publicRuntimeConfig: {
// Will be available on both server and client
baseUrl: 'http://localhost/api/v1',
},
serverRuntimeConfig: {
// Will only be available on the server side
baseUrl: 'http://backend_nginx_1/api/v1/',
},
am I missing something ?
This will sound dumb, but I spent 2 hours seeing the empty file been recognized by the system and just seeing {}.
Now... restarting the server, gives you access to the content of the file.
That was my solution.
And it was not included in the documentation.
https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration

Why does my app return 304 status code when started with node but not with nodemon

I've created a basic app which can take notes, and I'm using a .json file to store them. This is part of an assignment where I was given the front-end code and then had to create the Express back end.
Throughout development I used nodemon to run the server, but I needed to host on heroku so I've changed it to start with node instead, however now my GET requests in the fetch method are returning 304, even when the database has definitely been modified. POST and DELETE both still work and modify the database but GET doesn't even after refreshing the page. I have to stop the server and start it again for the fetch request to work.
The code making the request:
const getNotes = () =>
fetch('/api/notes', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
Express code used to respond:
app.get('/api/notes', (req, res) => res.json(database));
Any help is much appreciated.

$.ajax has no request payload for absolute filesystem path

Note: I explain the strange urls in a spoiler below.
Electron#2.0.4
jquery#3.3.1
When I try to use $.ajax to an absolute path from within Electron jquery seems to get rid of my payload. I use the following:
$.ajax({
url: "/test/anything?func=ajax",
method: "POST",
processData: false,
contentType: "application/json",
data: JSON.stringify({foo: "bar"}),
});
fetch("/test/anything?func=fetch", {
method: "POST",
mode: "cors",
body: JSON.stringify({foo: "bar"})
});
They produce the following requests:
As you can see, the ajax call has no payload while the fetch does. Does anyone know a way to fix this or if there is a reason for this behavior?
As for the strange URL, I use a service worker to forward urls that start with /test to http://localhost, that's working properly as pictured below. Localhost is just for testing, I have a local copy of httpbin running on docker.
I am doing this to port a web app to electron so the codebases can be the same, aside from index.html changes and adding sw.js.
Thanks to Rory's comment above, I found a solution. I installed express and added the an express.js file to the project root, with the contents:
const express = require('express')
const app = express()
app.use(express.static('.'))
app.listen(3000)
Using this gist, I added the following to various places in my main.js file:
const express = require('./express.js'); //<
function createWindow () {
mainWindow.loadURL('http://localhost:3000/index.html'); //<
}
The service worker still gets the request, and it replaces the http://localhost:3000/test with http://localhost
ajax:
service worker:
The service worker also sends an OPTIONS request to make sure cross domain is allowed, while the fetch's request doesn't. This seems to be because the ajax request has an X-Requested-With header, while the fetch doesn't.

Ionic v2 + CORS Preflight Access-Control-Allow-Methods

Having issues communicating with an external API via ionic serve and ionic run -l, essentially anything that uses a localserver.
I've followed the guide # http://blog.ionic.io/handling-cors-issues-in-ionic/, which provides an option for handling the issue in Ionic 1 projects, but I'm struggling to get it working in a v2 project.
Fetch API cannot load https://test.api.promisepay.com/items/100fd4a0-0538-11e6-b512-3e1d05defe79/make_payment. Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response.
I have no control over how the API handles theses requests, as it is controlled by PromisePay.
Following the closest thing to a possible solution on StackOverflow: CORS with Firebase+IONIC2+Angularjs: No 'Access-Control-Allow-Origin' still exists
I've updated my ionic.config.json to
{
"name": "project",
"app_id": "xxxxxxx",
"proxies": [{
"path": "/api",
"proxyUrl": "https://test.api.promisepay.com"
}]
}
In the library that makes the http calls, I've updated the base URL to const PRE_LIVE_API = '/api';
The request method looks as follows:
let Requester = class Requester {
constructor() {
let config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.config = config;
const baseUrl = PRE_LIVE_API;
this.log(`API endpoint: ${ baseUrl }`);
this.client = _requestPromise2.default.defaults({
baseUrl: baseUrl,
auth: {
user: config.userName,
pass: config.token
},
headers: {
Accept: 'application/json',
Authorization: `basic ${ config.apiToken }`
},
resolveWithFullResponse: true
});
}
When making a call to the most basic of API endpoints /status/ I am now receiving the following error:
"Error: Invalid URI "/api/status""
It seems the proxy path isn't being passed through.
I was facing the same problem when I was trying to use the MailGun to send e-mails using REST API.
The solution is to use HTTP instead of http. ionic 2 provides the class [HTTP]: http://ionicframework.com/docs/v2/native/http/ .
In your projects root folder, run this command from the terminal:
ionic plugin add cordova-plugin-http
In your .ts file:
import { HTTP } from 'ionic-native';
Then, wherever you want to send the HTTP post/get using Basic Authentication, use this:
HTTP.useBasicAuth(username, password)
//replace username and password with your basic auth credentials
Finally, send the HTTP post using this method:
HTTP.post(url, parameters, headers)
Hope this helps! Good luck!
For Development purposes where the calling url is http://localhost, the browsers disallow cross-origin requests, but when you build the app and run it in mobile, it will start working.
For the sake of development,
1. Install CORS plugin/Extension in chrome browser which will help get over the CORS issue.
2. If the provider is giving a JSONP interface instead of a normal get/post, You will be able to get over the CORS issue.
I prefer using the 1st option as not a lot of api's provide a jsonP interface.
For Deployment,
You need not worry as building a app & running it in your mobile, you will not face the same issue.
Solved. Explicitly setting the BaseURL constant (PRE_LIVE_BASE) to http://localhost:8100/api resolves the issue. Now all requests are passed via the proxy alias and subvert the CORS issue.
The only downside of this approach, is that I had to change a variable that was part of a package in node_modules, which will be overwritten during any future updates. So I should probably create my own fork for a cleaner solution.

Categories

Resources