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.
Related
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.
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.
I have an ExpressJS server built on NodeJS which I'm trying to POST to using fetch() and a route file named test. I have a form on my external website that needs to submit data to the server. When testing this, I receive the following error in the console:
submit.html:228 OPTIONS https://domain/test 0 ()
setOutcome # submit.html:228
Promise.then (async)
(anonymous) # submit.html:272
Error: TypeError: Failed to fetch
This is the fetch() statement, which works fine in other examples when used in files hosted on the Express server where my domain is, just not when trying to fetch externally:
fetch('https://domain/test', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
data: 'test'
})
})
Should I be using fetch() to communicate with my Express server externally or should I be using something else? Sorry, I am new to this and trying to find my feet.
Additionally, I can't see that the server has even received a request in my server log files. If doing this on the Express server, I'll normally see a GET or POST in the logs.
I have the following function (essentially taken straight from the answer to another SO question):
function makePostRequest(requestURL, postData) {
request(
{
url: requestURL,
method: "POST",
json: true,
body: postData
},
function(error, response, body) {
console.log(response);
});
}
When I call it with the right requestURL, I successfully reach this route:
router.post("/batchAddUsers", function(req, res) {
console.log("Reached batchAddUsers");
});
I've been trying to retrieve the postData I sent with the request to no avail. Both req.params and req.body are {}. I haven't got the faintest clue how to refer to the object containing body passed in the request.
I read the whole console.log(req) and found nothing useful. I've done this kind of stuff before, except the request was made by a form and req.body worked like a charm. Now that I'm doing the request "manually", it doesn't work anymore. The whole thing is running on Node.js.
What am I doing wrong?
I think you did not insttalled body-parser
To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser.
body-parser extract the entire body portion of an incoming request stream and exposes it on req.body .
The middleware was a part of Express.js earlier but now you have to install it separately.
This body-parser module parses the JSON, buffer, string and url encoded data submitted using HTTP POST request. Install body-parser using NPM as shown below.
npm install body-parser --save
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.