Can't send/receive a header with axios and python - python

I`m trying to send custom headers in a post request with axios in the following way:
const onSubmit = async (data) => {
const token = await getAccessTokenSilently();
console.log(token);
const header = {
headers: {
'Authorization': `Bearer ${token}`
}
};
const body = {
source: "website",
user_id: user.sub,
message_category: "crypto",
message_text: data,
};
console.log(body);
axios
.post(serverUrl + "messages/post_message", body, header)
.then((res) => {
// setPosts(res.data.messages);
console.log(res);
})
.catch(function (error) {
// handle error
console.error(error);
});
};
But in my python cherrypy server I`m not getting the custom headers at all. although I do receive it in Acess-Control-Request-Headers as titles without the data.
debugging: auth = cherrypy.request.headers in python:
PS: Sending headers via postman works normally.

Considering that your API is working correctly (you might recheck that as well). See if this works for you:
const onSubmit = async (data) => {
const token = await getAccessTokenSilently();
const options = {
headers: {
'Authorization': `Bearer ${token}`
},
body: {
source: "website",
user_id: user.sub,
message_category: "crypto",
message_text: data,
}
};
axios
.post(serverUrl + "messages/post_message", options)
.then((res) => {
// setPosts(res.data.messages);
console.log(res);
})
.catch(function (error) {
// handle error
console.error(error);
});
};

Related

Server Error in Android Volley Request Status Code 500

I have deployed an Flask API in Heroku. Trying to hit the Flask API through Android Volley POST request. But the log file shows NetworkUtility.shouldRetryException: Unexpected response code 500.
I have Tested on Postman.it works perfect.I don't know what is the problem, stuck here for 2 days.
My URL for the Heroku app is correct.
In my Heroku app log file : also shows an error "TypeError: expected string or bytes-like object".
Here is my MainActivity.java :
public class MainActivity extends AppCompatActivity {
EditText question;
Button btn;
TextView textView;
Button reset;
String url = "https://krishokbot.herokuapp.com/chatbot";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
question = (EditText) findViewById(R.id.question);
btn = (Button) findViewById(R.id.btn);
textView = (TextView) findViewById(R.id.textView);
reset = (Button) findViewById(R.id.reset);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StringRequest stringRequest = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String data = jsonObject.getString("response");
textView.setText(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Volley", "Error. HTTP Status Code:" + networkResponse.statusCode);
}
if (error instanceof TimeoutError) {
Log.e("Volley", "TimeoutError");
} else if (error instanceof NoConnectionError) {
Log.e("Volley", "NoConnectionError");
} else if (error instanceof AuthFailureError) {
Log.e("Volley", "AuthFailureError");
} else if (error instanceof ServerError) {
Log.e("Volley", "ServerError");
} else if (error instanceof NetworkError) {
Log.e("Volley", "NetworkError");
} else if (error instanceof ParseError) {
Log.e("Volley", "ParseError");
}
Log.d("Maps:", " Error: " + error.getMessage());
}
}) {
#Override
protected Map<String,String> getParams() {
Map<String,String> params = new HashMap<String, String>();
params.put("question", question.getText().toString());
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(stringRequest);
}
});
}
}
from flask import Flask, render_template, jsonify, request
import chatbot_response
app = Flask(__name__)
#app.route('/')
def index():
return "hello_world"
ar
#app.route('/chatbot', methods=['POST'])
def chatbotResponse():
question = request.args.get('question')
response = chatbot_response.chatbot_response(question)
return jsonify({"response": str(response)})
if __name__ == '__main__':
app.run()
Heroku log Image link : [https://ibb.co/jRtBfN4]

Axios then, catch are not called

In my React front end, I call Axios with post method successfully, in my Python Falcon backend parameters are received successfully and token is generated back,
problem is the code in .then or even .catch are never called, here is my front end code:
async submit() {
//var aluser = this.this.state.username;
await axios({
method: "post",
url: "http://127.0.0.1:8000/Login",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
},
params: {
username: this.state.username,
password: this.state.password
}
})
.catch(error => {
console.log(
"here is the error on a post request from the python server ",
error
);
})
.then(res => {
console.log(res);
sessionStorage.setItem("token", res.data[0]);
});
}
Note: the order of .then .catch was switched before, same result.
Thanks in advance
try to use try/catch
const params = new URLSearchParams();
params.append('username', this.state.username);
params.append('password', this.state.password);
async submit() {
//var aluser = this.this.state.username;
try {
const res = await axios({
method: "post",
url: "http://127.0.0.1:8000/Login",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
},
params
})
sessionStorage.setItem("token", res.data[0]);
} catch (err) {
console.log(
"here is the error on a post request from the python server ",
error
);
}
}
If your backend service is only returning a 200 response, axios will not call "then" because you haven't send response data back. I just sent an "OK" response payload back with my 200 status code. "then" was called as expected.

Node JS and Python - POST image from Node JS to Python REST API

I have a Node JS application. I want to send an image from the Node JS application to a REST API which is written in Python. The key and the inputs needed by the Python REST API are as follows
My problem is that I am able to POST a simple 'Hello World' string with the code I have written and get a response. However, when I try to send an image something goes wrong and I get no response.
var http = require('http');
var querystring = require('querystring');
// This is some dummy string data
var postData = querystring.stringify({
msg: 'hello world'
});
var fs = require('fs')
, path = require('path')
, certFile = path.resolve(__dirname, 'ssl/client.crt')
, keyFile = path.resolve(__dirname, 'ssl/client.key')
, caFile = path.resolve(__dirname, 'ssl/ca.cert.pem')
, request = require('request');
// I want to send an image from one server to another. What changes should I make to the options below for POSTing image data
var options = {
hostname: '127.0.0.1',
port: 8888,
path : '/predict',
//image: fs.createReadStream('car.jpg'), //Should I give something like this??
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': postData.length
}
};
var req = http.request(options, function (res) {
console.log('STATUS:', res.statusCode);
console.log('HEADERS:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY:', chunk);
});
res.on('end', function () {
console.log('No more data in response.');
});
});
req.on('error', function (e) {
console.log('Problem with request:', e.message);
});
req.write(postData);
req.end();
Please let me know what changes I have to make to this code to post an image.I read about the use of multer package. However, the examples that I came across were using JS on both ends. Since for me, I have a Python REST API , I cannot use that. PLease help since I have been struggling with it for some time now.
Edit 1: Based on #Jana's suggestion, I added the multipart within the options and tried, where image is the key and the value is fs.createReadStream('car.jpg') . However, at the python end, it does not get the 'image' key because of which I get a False response. What am I missing?
var options = {
hostname: '127.0.0.1',
port: 8888,
path : '/predict',
//image: fs.createReadStream('car.jpg'), //Should I give something like this??
multipart: [
{
'content-type': 'application/json',
body: JSON.stringify({'image': fs.createReadStream('car.jpg') })
}
],
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
//'Content-Length': postImageData.length
}
};
Check this,
`request({
method: 'POST',
uri: 'http://127.0.0.1:8888/predict',
multipart: [{
'content-type': 'application/json',
body: JSON.stringify({
"key": "value"
})
},
{
body: fs.createReadStream('car.jpg')
}
],
},
function(error, response, body) {
if (error) {
return console.error('upload failed:', error);
}
console.log('Upload successful! Server responded with:', body);
})`
And also you can get the best examples from its own documentation Request - Simplified HTTP client

Cannot retrieve data from endpoint

I have installed Chatterbot for Django integration. I followed the easy tutorial with every step and made it so that the endpoint was: http://127.0.0.1:8000/chatterbot/ What I did next was try to communicate with that endpoint to see if I would get back any results. So I made an Ajax request as follows:
var query = {"text": "My input statement"};
$.ajax({
type: 'POST',
url: "http://127.0.0.1:8000/chatterbot/",
data: JSON.stringify(query),
contentType: 'application/json',
success: function (data) {
console.log(data);
}
});
However, what returns in console is: POST http://127.0.0.1:8000/chatterbot/ 403 (Forbidden) and what returns in the cmd prompt when I run my server is:
csrf: WARNING - Forbidden (CSRF token missing or incorrect.):
/chatterbot/ [29/Mar/2018 02:16:43] "POST /chatterbot/ HTTP/1.1" 403
2502
Why am I getting this error? How can I fix it so I receive the call back from the endpoint?
View for this page:
def IndexView(request):
latest_questions = Questions.objects.all().order_by("-date_published")[:5]
popular_questions = Questions.objects.all().order_by("-num_replies")[:5]
return render(request, 'core/index.html',
{'latest_questions': latest_questions, 'popular_questions': popular_questions
})
Try this code
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
var query = {
"text": "My input statement",
"csrfmiddlewaretoken": csrftoken
};
$.ajax({
type: 'POST',
url: "http://127.0.0.1:8000/chatterbot/",
data: query,
contentType: 'application/json',
success: function (data) {
console.log(data);
}
});
one way is to send the csrfmiddlewaretoken like below
var query = {
"text": "My input statement",
'csrfmiddlewaretoken': "{{csrf_token }}"
};
other way is to use #csrf_exempt decorator
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def IndexView(request):
# .... code.....
other is to add a script
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Reference: https://docs.djangoproject.com/en/2.0/ref/csrf/
If you dont want to use CSRF tokens just add this above your code.
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def IndexView(request):
# your code

CSRF With Ajax Polling

I have some AJAX that polls the server every 5 seconds:
var date = $('article').first().find('time').text();
console.log(date);
setInterval(function() {
$.post('pollNewEntries', {'date':date}, newEntrySuccess)
}, 5000);
Unfortunately, I'm getting a 403 error every time the AJAX tries to poll the server, stating that I have made an invalid CSRF request. I've used AJAX with forms before and included the CSRF token within the forms, but I"m not sure how I would do it with a formless AJAX request like above.
The solution to this problem is described in the Django documentation: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
Add this code to the top of your js:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
You need to pass csrf token along with your post data:
var date = $('article').first().find('time').text();
console.log(date);
setInterval(function() {
$.post('pollNewEntries', {'date':date, 'csrfmiddlewaretoken': '{{csrf_token}}'}, newEntrySuccess)
}, 5000);
Simply add these lines in your script. Here is an example in coffeescript :
### CSRF methods ###
csrfSafeMethod = (method) ->
# these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method))
$.ajaxSetup(
crossDomain: false
beforeSend: (xhr, settings) ->
if !csrfSafeMethod(settings.type)
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'))
)
Read the documentation : CSRF
In other hand, as user1427661 suggests to you, it will be better to use HTTP GET method instead of POST, because you only need to read data and don't write anything. See the W3 docs.

Categories

Resources