MeteorJS HTTP POST Request Connection Lost XMLHttpRequest - python

I am writing an application that integrates into a website that is already written in Meteor (I can't change that but I can add on to it). I am trying to send information from the Meteor application to my Flask server.
To do this I am using MeteorJs's HTTP module.
The code for this:
HTTP.post('http://127.0.0.1:5000/path', {
"content" : {"headers" : {"Content-Type": "application/json"}, "data": {time: getTime, data: getData()}}
},
(error, result) => {
if(error){
console.log(error);
console.log({time: getTime(), data: getData()})
}
else {
console.log(result);
}
}
)
getTime() and getData() both work independently outside this function, so they shouldn't be the source of error.
When I look at the JS console for when the event is being fired I receive the following message:
Error: Connection lost at XMLHttpRequest.xhr.onreadystateexchange and what was supposed to be sent to the Flask server.
When I look at the Flask server I see that it is receiving the post request with status code 200, but it seems like there is no data actually being received.
The code on the python end:
#app.route(r'path', methods=["POST"])
def get_data():
print(request.data)
print(request.args)
return "Hello World"
The print statements come out empty with this being shown on the console b'[object Object]' or ImmutableMultiDict([])
The Meteor app and the Flask app are both on different ports.
The problem I believe is on the MeteorJS side, since I used the curl linux function it works properly when I ping the flask server from there.
Is there a way to fix this error? If so how?

Hi "parameters" should be "data".
You can find all valid options in the docs.
Let me know if it works for you.
HTTP.post('http://127.0.0.1:5000/path', {
data : {time: getTime(), data: getData()}
}, (error, result) => {
if(error){
console.log(error);
console.log({time: getTime(), data: getData()})
} else {
console.log(result);
}
}
)

Related

Swift HTTP session not sending actual Request

So I have some Swift code that send a request to my local host
//
// ContentView.swift
// Shared
//
// Created by Ulto4 on 10/23/21.
//
import SwiftUI
struct ContentView: View {
var body: some View {
VStack{
Text("Hello, world!")
.padding()
Button(action : {
self.fu()
}, label: {
Image(systemName: "pencil").resizable().aspectRatio(contentMode:.fit)
})
}
}
func fu(){
let url = URL(string: "http://127.0.0.1:5000/232")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error took place \(error)")
return
}
if let response = response as? HTTPURLResponse {
print("Response HTTP Status code: \(response.statusCode)")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}
However, on my Flask app there are no get requests coming in and the function isn't running. There also isn't anything printing to the console.
I am fairly new to swift so I don't really know how to fix this.
Is there any other way to send requests in swift, if not, How would I fix this?
You are creating the URLSessionDataTask, but you never start it. Call task.resume(), e.g.
func performRequest() {
guard let url = URL(string: "http://127.0.0.1:5000/232") else {
fatalError()
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error took place \(error)")
return
}
if let response = response as? HTTPURLResponse {
print("Response HTTP Status code: \(response.statusCode)")
}
}
task.resume() // you must call this to start the task
}
That having been said, a few caveats:
You are doing http rather than https. Make sure to temporarily enable insecure network requests with app transport settings, e.g.
You didn’t say if this was for macOS or iOS.
If running on physical iOS device, it will not find your macOS web server at 127.0.0.1 (i.e., it will not find a web server running on your iPhone). You will want to specify the IP number for your web server on your LAN.
If macOS, make sure to enable outbound network requests in the target’s “capabilities”:
You asked:
Is there any other way to send requests in swift?
It is probably beyond the scope of your question, but longer term, when using SwiftUI, you might consider using Combine, e.g., dataTaskPublisher. When running a simple “what was the status code” routine, the difference is immaterial, but when you get into more complicated scenarios where you have to parse and process the responses, Combine is more consistent with SwiftUI’s declarative patterns.
Let us consider a more complicated example where you need to parse JSON responses. For illustrative purposes, below I am testing with httpbin.org, which echos whatever parameters you send. And I illustrate the use of dataTaskPublisher and how it can be used with functional chaining patterns to get out of the mess of hairy imperative code:
struct SampleObject: Decodable {
let value: String
}
struct HttpBinResponse<T: Decodable>: Decodable {
let args: T
}
class RequestService: ObservableObject {
var request: AnyCancellable?
let decoder = JSONDecoder()
#Published var status: String = "Not started yet"
func startRequest() {
request = createRequest().sink { completion in
print("completed")
} receiveValue: { [weak self] object in
self?.status = "Received " + object.value
}
}
func createRequest() -> AnyPublisher<SampleObject, Error>{
var components = URLComponents(string: "https://httpbin.org/get")
components?.queryItems = [URLQueryItem(name: "value", value: "foo")]
guard let url = components?.url else {
fatalError("Unable to build URL")
}
return URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: HttpBinResponse<SampleObject>.self, decoder: decoder)
.map(\.args)
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
}
struct ContentView: View {
#ObservedObject var requestService = RequestService()
var body: some View {
VStack{
Text("Hello, world!")
.padding()
Button {
requestService.startRequest()
} label: {
Image(systemName: "pencil").resizable().aspectRatio(contentMode:.fit)
}
Text(requestService.status)
}
}
}
But, like I said, it is beyond the scope of this question. You might want to make sure you get comfortable with SwiftUI and basic URLSession programming patterns (e.g., making sure you resume any tasks you create). Once you have that mastered, you can come back to Combine to write elegant networking code.
FWIW, like workingdog said, you could also use the new async-await rendition of data(for:delegate:). But when in the declarative world of SwiftUI, I would suggest Combine.

Can not get python file output using node.js

I am trying to fetch python output from Node.js script using postman but unable to get the required output. I am explaining my code below.
app.js:
router.post('/usecase-workflow', async (req, res) => {
try{
let responseUsecase = await usecaseWorkflow.fetchUsecaseWorkflow(req);
res.send(responseUsecase);
}catch(error) {
responseObj = {
status: 'error',
msg: 'Error occurred while downloading ubot file',
body: error
}
res.send(responseObj);
}
})
usecaseWorkflow.js:
const mongoose = require('mongoose');
const axios = require('axios');
const request = require('request');
class DefineUseCase {
fetchUsecaseWorkflow = async(req) => {
try{
const response = await axios.post('http://127.0.0.1:5005/usecase-workflow',req);
//console.log(response);
return response;
}catch(error) {
console.log(error);
}
}
}
module.exports = new DefineUseCase();
When I am doing REST API call from postman the above code is executing. I am giving the screen shot of postman below.
Here my need is i will upload one zip file and one node.js REST API will call. Inside the node script I am calling one python file to get the final output. But as per my code its not giving any result. If I am calling the Python file directly from postman Its giving some result. I am also giving python call postman screen shot below.
So here I need to fetch the same above output via node.js REST API.

I am getting jQuery Jtable error while fetching data from the python server

I have a jQuery Jtable in the front end and I am using python flask in my server.
I used python flask to fetch data from the MYSQL server which I can view in the JSON format in my browser but, unfortunately I couldn't able to make the JSON data into the Jtable.
My front end jQuery Jtable is
$('#eventsummary').jtable({
actions: {
listAction: function (postData) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/backend/groupdata',
type: 'GET',
data: postData,
success: function (data) {
$dfd.resolve(data);
console.log("loading ");
},
});
});
}
},
fields: {
irs_type: {
title: "Date & Time",
list: true,
}
}
});
$('#eventsummary').jtable('load');
and this is the error I am getting
I am also able to view my console.log code in the browser, with no error in the console.
Can someone please help me with this
Thanks,
I achieved this by using python jsonify to add my json data to the front end Jtable.
for result in data:
json_data.append(dict(zip(row_headers,result)))
return jsonify(
{
'Result': "OK",
'Records': json_data,
}
)
Thanks
The output you are seeing is the standard jTable application error. Your listAction has passed the server response to jTable, so there is no communications error.
When the json response does NOT contain Result = 'OK' it displays the application error dialog, and shows the json Message in the dialog.
The very fact that the error dialog appears means jTable is not seeing Result = 'OK' in your server response. Look for that first, if you are still stuck please post your json response. The dialog is blank because there is no error message or jTable can't see it.

(Fine uploader) Error uploading file to s3 using external ec2 server as signature handler

I been struggling for a couple of days trying to get this working. So now I thought I'd ask for some help.
I'm not able to sign headers and I don't know how to proceed. I have followed this guide to every detail: https://blog.fineuploader.com/fine-uploader-s3-upload-directly-to-amazon-s3-from-your-browser-3d9dcdcc0f33#sign-policy
This is my setup:
Javascript to handle upload:
var uploader = new qq.s3.FineUploader({
element: document.getElementById("uploader"),
debug: true,
request: {
endpoint: 'my-bucket.s3-accelerate.amazonaws.com',
accessKey: 'my-access-key'
},
signature: {
endpoint: 'my-external-signature-server'
},
uploadSuccess: {
endpoint: 'my-external-signature-server/s3/success'
},
iframeSupport: {
localBlankPagePath: '/success.html'
},
validation: {
allowedExtensions: ["jpeg", "jpg", "png"],
acceptFiles: "image/jpeg, image/png",
sizeLimit: 10000000,
itemLimit: 1
},
retry: {
enableAuto: true // defaults to false
},
paste: {
targetElement: document,
promptForName: true
}
});
Server setup:
Python flask enviornment set up according to the github example: https://github.com/FineUploader/server-examples/tree/master/python/flask-fine-uploader-s3. I have set it up according to the setup. Do I need to do more? Create my own policy documents or is everything included in the app.py file?
The app is running and publicly available by it's url. This is the url I link to in the signature endpoint above.
I get the following error when I try to upload an image:
GET https://cdn.shopify.com/s/files/1/2116/3741/t/1/assets/edit.gif 404 ()
OPTIONS https://my-external-signature-server/ net::ERR_CONNECTION_REFUSED
s3.fine-uploader.js?11308611504760701622:165 [Fine Uploader 5.15.5] POST request for 0 has failed - response code 0
[Fine Uploader 5.15.5] Received an empty or invalid response from the server!
[Fine Uploader 5.15.5] Policy signing failed. Received an empty or invalid response from the server!
my-external-signature-server is of course a stand in term.
I hope someone has an idea what could be wrong?
I'll gladly provide more information if necessary.

Request.files object is empty on flask server when uploaded using ng-file-upload

I am using ng-file-upload to upload a xls or xlsx file, below is my html code
<div ngf-drop ngf-select ngf-change="checkFile($invalidFiles);" ngf-model-invalid="invalidFiles" ng-model="file" class="center" ngf-drag-over-class="'dragover'" ngf-pattern="'.xls,.xlsx'">
<button class="some-class" ng-click="upload(file)"></button>
Angular controller:
$scope.upload = function (file) {
if (file) {
var upload = Upload.upload({
url: API.url('upload'),
data: {
file: file
},
headers:{ // tried passing different headers as well
"Content-Type":"multipart/form-data"
}
});
upload.then(function (resp) {
//Some Operation
}, null, function (evt) {
//Some Operation
});
}
};
Flask server:
def upload(self):
params = self.get_params(request)
file = request.files['file'] ###This object is empty.
result = self._upload_file(file)
return "Dummy"
I followed this documentation for server side.
I think the problem is from client side, may be I am sending some bad request as flask server is throwing 400. So I have tried by sending 'multipart/form-data' headers but no luck and also by sending Form data explicitly.
I have also looked for few solutions like sol-1.
I didn't find anything which could solve my problem in the ng-file-upload doc as well.
If required I can send the request headers as well.
I might be missing very tiny part, can someone please point me out that.
There is default value for headers which is already in post request. Adding "Content-Type":"multipart/form-data" is just overriding that. Try it without that.

Categories

Resources