I'm trying to use Parse Cloud Code to run a python script. I'm passing a parameter, but I seem to be getting an error. I'm not 100% sure what the problem is, but it seems like I'm not composing the url correctly. Any help would be appreciated.
My python code looks like this:
# a function that makes a sentence more exciting
def excited(sentence):
return sentence + '!!!'
Here's my code in main.js:
Parse.Cloud.define('testFunction', function(request, response) {
var someParam = request.params['testString'];
var url = 'http://mywebsite.com/test.py/excited&sentence=' + someParam;
Parse.Cloud.httpRequest({
url: url,
success: function(httpResponse) {
console.log(httpResponse.headers);
console.log(httpResponse.text);
response.success();
}, error: function(httpResponse, error) {
console.error('Request failed with response code ' + httpResponse.status);
}
});
});
EDITED:
Now I understand the problem better.
You are trying to call a python method from Parse.Cloud javascript based service. Based on their tutorials, I think you probably wanted the other way round.
Parse.Cloud allows you to deploy some server-side code in javascript. Then you can make REST API calls from your mobile app to the server endpoints by using either python or curl or any other language or tool. While testing, you can just call the end points from python on your box.
So your server code (in cloud/main.js) should look like this:
Parse.Cloud.define("testFunction", function(request, response) {
var excitedSentence = request.params.testString + "!!!";
response.success(excitedSentence);
});
This code creates a REST API endpoint at https://api.parse.com/1/functions/testFunction
Then you can call this API endpoint by using python (assuming you have Python installed on your box):
import json,httplib
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
connection.request('POST', '/1/functions/testFunction', json.dumps({
"testString": "This is an example sentence"
}), {
"X-Parse-Application-Id": "xxxxx_PUT_YOUR_ID_xxxxxxx",
"X-Parse-REST-API-Key": "xxxxxxxx_YOUR_KEY_xxxxxx",
"Content-Type": "application/json"
})
result = json.loads(connection.getresponse().read())
print result
If you don't have python installed, you can call the API endpoint by going to the online dashboard.
Go to: Your App -> Core tab -> API Console.
For endpoint, select post (this is important), and specify "functions/testFunction" in the text box.
In request body, specify: {"testString" : "This is an example sentence"}
Click "Send Request" and you should see the following output:
"result": "This is an example sentence!!!"
Related
I have some javascript sending GET request to a python server. It's all been good when I run the server on localhost. Like this:
js:
$.get({
url: 'http://localhost:7973/loadPage',
success: function(result){pageLoadSucceed(result);},
error: function(error){requestFailed(error);}
});
python:
import tornado.web
import tornado.ioloop
def make_app():
return tornado.web.Application([
(r'/loadPage', LoadPageHandler)
])
if __name__ == '__main__':
app = make_app()
app.listen(7973)
tornado.ioloop.IOLoop.current().start()
Now, I moved the service to an EC2 Windows Server on AWS. The service still launches fine. However, when I making requests from my machine with the code below, it fails (timeout).
modified js:
$.get({
url: 'http://Administrator:eX%f4TYtaJLu*YCdt$Nm;le7$tmfqLv3#ec2-xx-xxx-xx-xxx.us-east-2.compute.amazonaws.com:7973/loadPage',
success: function(result){pageLoadSucceed(result);},
error: function(error){requestFailed(error);}
});
Since in browser (chrome), the same url gives me an ERR_CONNECTION_TIMED_OUT, I assume my url is wrong.
But I am just not sure how it is wrong - is one of the ingredients (address, username, password) is wrong or did I piece them together wrong? The ingredients I got from the AWS page after clicking "Connect" as shown below:
Thanks in advance!
I am trying to communicate with a 3rd party API. I wrote the API in python. I want to update the name column in the database from the Wix web page using a user form and text box. The database updates and all of the endpoints are responsive using postman to test. I think the problem resides in my JavaScript on the Wix end.
I modeled the JavaScript from the Wix example at:
https://support.wix.com/en/article/calling-server-side-code-from-the-front-end-with-web-modules
I have a back end module called placeOrder stored in orderplaced.jsw that should post the variable 'name' to the api.
import { fetch } from 'wix-fetch';
// wix-fetch is the API we provide to make https calls in the backend
export function placeOrder(name) {
return fetch("https://reliableeparts.pythonanywhere.com/user", {
method: 'post',
name: JSON.stringify({ name })
}).then(function (response) {
if (response.status >= 200 && response.status < 300){
console.log(JSON.stringify({ name }))
return response.text();}
console.log(Error(response.statusText))
return Error(response.statusText);}
);
}
The front end module waits for a button click and stores the text box in the name variable.
{
import {placeOrder} from 'backend/orderplaced.jsw';
export function button1_click(event, $w) {
placeOrder(
$w("#input1").value)
.then(function() {
console.log("Form submitted to backend.");
}
);
}
}
Output:
2
The code appears to be reaching the back end. I believe the problem is in my placeOrder function as I am not very familiar with JavaScript.
Your code seems legit. The problem is with the server. When I tried to send a POST request to that address I got a 500 Internal Server Error.
You may check this curl and test the service yourself:
curl -i -X POST -H "Content-Type:application/json" https://reliableeparts.pythonanywhere.com/user -d '{"name":"test123"}'
You are probably missing the correct object structure the server is expecting or missing proper headers to POST the server (or both...)
Make sure you're following the API this server allows
I'm just following tutorials and figuring out how to handle get requests in NodeJS.
Here are snippets of my code:
NodeJS:
router.get('/test', function(request, response, next) {
console.log("Received Get Request");
response.jsonp({
data: 'test'
});
});
Angular:
$http.get("http://localhost:3000/test").
success(function(response) {
alert("OK");
}).
error(function(response) {
alert("FAIL");
});
If I try to access the link directly # localhost:3000/test, I'm able to receive the JSON message correctly. But when I use angularJS $http call, the request always fails and I'll find this error in the network inspector (Response)
SyntaxError:JSON.parse:unexpected end of data at line 1 column 1 of
the JSON data
The reason for that is because the response is empty but the response code is 200 in both cases.
I've tried searching for hours but maybe someone can enlighten me on this?
you could try and send
res.send('test')
and then on your http request you can use 'then'
$http.get("http://localhost:3000/test").then(function(res) {
console.log(res);
})
unlike success, then will give you a complete object (with 'test' - string as res.data)
success will bring you only the data;
then will bring you the whole object (with the status and such)..
now about that jsonp .. it's used to override a json response. you could simply use 'res.json({data: 'test'})' and it should also work for you..
hope it helps
You're using jsonp in node, which you probably don't need to. This adds extra characters to the response and so the JSON parser fails to parse (that's what the error is telling you, the JSON is malformed)
Try changing the server to look like
response.json({
data: 'test'
});
If you look in the Network pane of the developer tools, you should be able to see the raw response. It should look something like:
{"data" : "test"}
I am new to Node.js and this is my first project with it.
I have made a node.js file named test.js. It has an array say a.
Now I want to make a HTML file that calls this test.js on button click event. Then get the data from that file and publish it on a table in the HTML file.
I have already written the node.js file and I can see the results on console.log(a). But I cant understand how to send this array to HTML when it will ask for it.
Meanwhile, I googled and made up some code. The request reaches the server but I always get error response from server. Why so?
Client Side -
function fetch() {
$.ajax({
type: 'POST',
url: "http://127.0.0.1:8888",
data: 'China',
datatype: 'json',
success: function (data) {
alert("hi");
var ret = jQuery.parseJSON(data);
$('#q').html(ret.msg);
},
error: function (xhr, status, error) {
alert("hii");
}
});
Server side :
http.createServer(function(request, response) {
console.log("Request received");
response.writeHeader(200, {"Content-Type": "application/json"});
request.on('data', function (chunk) {
console.log(chunk.toString('utf8'));
consol.log(result);
response.write(JSON.stringify({data : result}));
});
response.end();
}).listen(8888);
I can see China on the console.But I dont get back the result array back to the client. Here result is an array and I get its value on the console. Just that I dont get it back to the client. Any help ?
You should start by setting up a server to serve requests. I use expressjs for this - http://expressjs.com/
This will allow you to run nodejs as a web application.
Setup a route in express JS to serve your data - http://expressjs.com/api.html#express
var express = require('express');
var app = express();
app.get('/data', function(req, res){
res.send('hello world'); //replace with your data here
});
app.listen(3000);
Open up a browser, and type in http://MY_SERVER_ADDR:3000/data and you should see your output there.
Next, you'll need to attach an event handler to your HTML file that will trigger a $.get() request when it is triggered. Add the previous url to your data in your $.get call and do something with it.
$('.my_selector').click(function(){
$.get('http://MY_SERVER_ADDR:3000/data', {}, function(data){
console.log(data)
});
});
That should get you going.
After wrestling with the same question, i found that this is exactly where a template engine comes into the node-picture.
EJS solved it for me, but there are many more available.
This article compares 10 template engines.
The new custom API script allows a lot of customization through any type of connection.
I found that this website Custom API in Azure Mobile Services – Client SDKs describes the custom API.
var client = new WindowsAzure.MobileServiceClient('http://myservice.azure-mobile.net/', 'mykey');
client.invokeApi('query', {
method: 'POST'
});
But I couldn't run this code. It is supposed to show a message "Hello post World!".
I put the code inside tags in an HTML file and ran it but nothing happened.
Any help?
The call you have is making a call to your service, but it's ignoring its response. Assuming you have a custom API called 'query' (since it's what you're passing to invokeApi) with the following body:
exports.post = function(request, response) {
response.send(200, { message: 'Hello world' });
};
Your client code is calling it and (if everything goes fine) receiving the response, but it's not doing anything with it. There are a couple of ways to find out whether the call is being made. For example, you can add a log entry in the API and check the logs in your service:
exports.post = function(request, response) {
console.log('The API was called');
response.send(200, { message: 'Hello world' });
};
Or you can use a networking tool (the browser developer tools or Fiddler, for example) to see if the request is being made. Or you can actually do something with the result in the client side:
var client = new WindowsAzure.MobileServiceClient('http://myservice.azure-mobile.net/', 'mykey');
client.invokeApi('query', {
method: 'POST'
}).done(
function(result) { alert('Result: ' + JSON.stringify(result)); },
function(error) { alert('Error: ' + error); }
);
One thing which you need to look at if you're calling the API from a browser is whether the domain from where the page is being loaded is in the 'allow requests from host names' list, under the 'configure' tab, 'cross-origin resource sharing (cors)' section. If it's not, then you may get an error instead of the response you want.