While calling the python API from angular 10. I am getting multiple response. How to overcome it.
Python API Response from Angular Service call:
1. Object { type: 0 } # how to avoid this additional response
2. Object { headers: {…}, status: 201, statusText: "Created", url: "https://*********/1bcd2a20-dd60-4cfe-984f-7f3607f01e7c", ok: true, type: 4, body: "{\"status\":{}}" }
Angular Service Call:
postCall(identifier): Observable<HttpEvent<{}>> {
let token1 = localStorage.getItem('token');
const headerSettings: { [name: string]: string | string[]; } = {};
headerSettings['Authorization'] = 'Bearer ' + token1;
const req = new HttpRequest('GET', 'https://***********/'+identifier, null, {
reportProgress: false,
responseType: 'text'
});
const newHeader = new HttpHeaders(headerSettings);
let changedRequest = req.clone({
headers: newHeader
});
return this.http.request(changedRequest);
}
Related
I have a problem when send data from client that wrote by python to aws lambda. After that AWS Lambda send it to slack. Under is my code, I want to display "Message sent by raspi 1" but it displayed "Message sent by raspi undefined" in slack message.
Python file:
import requests
import json
url = 'https://.....execute-api.us-west-2.amazonaws.com/product/events'
data1 = json.dumps({'a': 1, 'b': 2})
x = requests.post(url, data = data1)
Lambda fuction:
var aws = require('aws-sdk');
const https = require('https');
exports.handler = (event, context, callback) => {
var responseBody = {
"key3": "value3",
"key2": "value2",
"key1": "value1"
};
var response = {
"statusCode": 200,
"headers": {
"my_header": "my_value"
},
"body": JSON.stringify(responseBody),
"isBase64Encoded": false
};
const payload = JSON.stringify({
text: `Message sent by raspi ${event.body.a}`,
});
const options = {
hostname: "hooks.slack.com",
method: "POST",
path: "https://hooks.slack.com/services/TPA2SP0GH/....",
};
const req = https.request(options,
(res) => res.on("data", () => callback(null, response)))
req.on("error", (error) => callback(JSON.stringify(error)));
req.write(payload);
req.end();
};
the event.body is a json string. you need to parse it before use it.
here:
const parsedBody = JSON.parse(event.body);
const payload = JSON.stringify({
text: `Message sent by raspi ${parsedBody.a}`,
});
Hope this helps.
Try accessing it with ${event['a']}. It is still a dictionary, not yet converted to an object.
I have Flask back-end and Angular front-end. My backend working well when I test it via Postman. I send the this kind of data
{
"date": "2018-01-27"
}
#app.route("/schedule", methods=['GET', 'POST'])
def schedule():
cursor = mysql.connection.cursor()
get_date = request.get_json(force = True)
day_name = datetime.datetime.strptime(get_date['date'], '%Y-%m-%d').strftime('%A')
week_number = datetime.datetime.strptime(get_date['date'], '%Y-%m-%d').strftime('%V')
...
But I have problems when I'm trying to send it from Angular.
My service :
#Injectable()
export class RequestService {
constructor(private http:Http) { }
getData(model): Observable<any>{
return this.http.post("http://127.0.0.1:5000/schedule",model)
.map((response:Response)=>{return response.json() });
}
}
My component:
export class CalendarComponent implements OnInit {
public myDatePickerOptions: IMyDpOptions = {
dateFormat: 'yyyy-mm-dd',
openSelectorOnInputClick: true,
satHighlight: true
};
data:any;
public model:any = { jsdate: new Date()};
constructor(private http:RequestService) { }
ngOnInit() {
}
getData(){
this.http.getData(this.model.formatted).subscribe(result => {
this.data = result;
});
console.log(this.model.formatted)
}
the error:
zone.js:2933 POST http://127.0.0.1:5000/schedule 400 (BAD REQUEST)
ERROR Response {_body: "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final/…object: Extra data: line 1 column 5 (char 4)</p>↵", status: 400, ok: false, statusText: "BAD REQUEST", headers: Headers, …}
And this is structure of this.model:
{date: {…}, jsdate: Sat Jan 27 2018 00:00:00 GMT+0300 (RTZ 2 (зима)), formatted: "2018-01-27", epoc: 1517000400}
What should I send to get a normal reponse?
Use this
this.http.getData({date: this.model.formatted})
And modify your post methot like that
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post("http://127.0.0.1:5000/schedule", JSON.stringify(model), {headers: headers})
Angularjs code
var app = angular.module('myApp', []);
app.factory('httpSend', ['$http', '$q', function($http, $q) {
var app = {};
app.sendToServer = function(data) {
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-type': 'application/x-www-form.urlencoded;'
}
}).then(function(response) {
debugger
var result = data;
});
}
app.getfromServer = function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
return app;
}]);
app.controller('myCtrl', ['$scope', '$http', 'httpSend', '$filter', function($scope, $http, httpSend, $filter) {
$scope.names = ["ankit patidar", "adhishi ahari", "kritin joshi", "kautilya bharadwaj", "punita ojha", "manvi agarwal", "apeksha purohit", "shipra jain", "mansi nangawat", "praveen soni"];
$scope.data = [];
$scope.names.forEach(function(name) {
$scope.data.push({
name: name,
checkin: "",
checkout: ""
})
});
$scope.login = [];
$scope.check = function(name, doing) {
debugger
name[doing] = new Date();
name[doing] = $filter('date')(name[doing], 'dd-MM-yyyy hh:mm:ss');
$scope.login.push(angular.copy(name));
if (doing == "checkout") {
var q = JSON.stringify($scope.login);
httpSend.sendToServer(q);
}
}
$scope.getData = function() {
httpSend.getfromServer();
}
}]);
`
Python Code
def get(self):
logging.info('get is triggered')
obj = CheckIn.query().fetch()
emp_obj = []
for x in obj:
logging.info('I am inside for loop ')
emp_obj.append({
'name': x.name,
'Check_in': x.inDate,
'check_out': x.outDate
})
logging.info('I am inside emp_obj')
self.response.write(json.dumps(emp_obj))
i need to fetch all the data stored on ndb datastore on front end view thats why i m using http get method but error is showed method not allowed. can u please help e despite using query fetch and showing its response on python ad triggering get method, why error is coming, is there a mistake in control flow or something is missing in my get method, as for now i m able to post nd store data
Change your factory to the following. Don't use the same variable app that you are using for initialising your module for your controller logic.
app.factory('httpSend',['$http', '$q',function($http, $q){
return {
'sendToServer': function(data) {
var def = $q.defer();
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
debugger
var result = response.data;
def.resolve(result );
});
return def.promise;
},
'getfromServer': function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
}
}]);
I am a new to Ajax/Python, I don't know how to POST a json value to my python server.
Python code:
#app.route('/ajouterContact', methods = ['POST'])
def ajouterContact():
data = json.loads(request.data)
#nom = request.form['nomContact'];
contact.append(data)
ajouter.make_response(json.dumps(contact), 201)
ajouter.headers['Content-Type'] = 'application/json'
JS code
$('#buttonAjouter').click(function() {
var nom = 'Tom';
var myObj = new Object();
myObj.nom = nom;
var jsonText = JSON.stringify(myObj);
var i = 0;
$.ajax({
url: '/ajouterContact',
data: jsonText,
type: 'POST',
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
I am getting this error on server side :
ValueError: No JSON object could be decoded
If anyone can help me on this..
Thank you!
You need to provide the contentType in your ajax request:
contentType: 'application/json;charset=UTF-8',
Then in your server try to debug something like this:
request.json
I've looked at many answers showing how to access a json in a python method however I can't seem to get mine to work.
Here is my ajax call
var data = {
'customer': customer,
'custID': custID,
'date': date,
'jobNum': jobNum,
'deviceID': deviceID
}
//create customer
if (custID === undefined) {
$.ajax({
url: "http://127.0.0.1:6543/test",
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
success: function(response, textStatus, jqXHR) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
}
else {
//empty
}
and here is my python method:
#view_config(route_name="test", renderer='templates/main.html')
def new_sheet(request):
response = request.POST
myObject = json.loads(response)
#print myObject["customer"]
test = "hello"
return dict(test=test)
somewhat new to python so pardon my limited understanding. How can I get my json and access the object properties? all i get in my cmd when i tried print was ValueError: No JSON object could be decoded
pyramid has native JSON request support. Set the contentType parameter to application/json to tell the server that you are sending JSON, preferably with a character set (UTF8):
$.ajax({
url: "http://127.0.0.1:6543/test",
type: "POST",
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
dataType: 'json',
success: function(response, textStatus, jqXHR) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
and on the server side use request.json_body:
#view_config(route_name="test", renderer='templates/main.html')
def new_sheet(request):
myObject = request.json_body
print myObject["customer"]
test = "hello"
return dict(test=test)