I am trying to call registration webservive in sencha.When I call it on browser its seems ok.But i calling with in the app its gives following error.Please any body help me.
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
here is my code
Ext.Viewport.setMasked({xtype:'loadmask',message:'your custom loadmask'});
Ext.data.JsonP.request({
url: 'http://XXX.XXX.com/api/users/?',
params: {
first_name:'mohit',
last_name:'bisht' ,
city:'ramnagar',
state:'UK',
phone:'9073467465',
email:'test#test.com',
password_digest:'123456',
op:'s'
},
success : function(response,opts) {
Ext.Viewport.setMasked(false);
console.log(response.status);
},
failure : function(response,opts) {
Ext.Viewport.setMasked(false);
if (response.timedout) {
Ext.Msg.alert('error', 'Request to server timed out.');
}
else if (response.aborted) {
Ext.Msg.alert('error', 'Request Aborted by server.');
}
else {
Ext.Msg.alert('error', 'Invalid Request to server.');
}
}
});
Are you sure the service supports jsonp? you can try with an ajax request instead:
Ext.Viewport.setMasked({xtype:'loadmask',message:'your custom loadmask'});
Ext.Ajax.request({
useDefaultXhrHeader: false,
cors: true,
url: 'http://XXX.XXX.com/api/users/?',
params: {
first_name:'mohit',
last_name:'bisht' ,
city:'ramnagar',
state:'UK',
phone:'9073467465',
email:'test#test.com',
password_digest:'123456',
op:'s'
},
success : function(response,opts) {
Ext.Viewport.setMasked(false);
console.log(response.status);
},
failure : function(response,opts) {
Ext.Viewport.setMasked(false);
if (response.timedout) Ext.Msg.alert('error', 'Request to server timed out.');
else if (response.aborted) Ext.Msg.alert('error', 'Request Aborted by server.');
else Ext.Msg.alert('error', 'Invalid Request to server.');
}
});
Hope it helps-
Related
It's my first question on Stackoverflow, normally I always found a solution here before Asking but not this time 😄
I use integration lambda mode, not the proxy mode.
I am able to set a cookie from serverless but I don't want to have the cookie in the body of my response.
I do this in the serverless.yml to set the cookie:
login:
handler: functions/auth/login.handler
events:
- http:
path: login
method: post
cors: true
integration: lambda
response:
headers:
Set-Cookie: integration.response.body.body
statusCodes:
200:
pattern: '' # Default response method
400:
pattern: '.*"statusCode": 400,.*'
template: $input.path("$.errorMessage")
401:
pattern: '.*"statusCode": 401,.*'
template: $input.path("$.errorMessage")
500:
pattern: '.*"statusCode": 500,.*'
template: $input.path("$.errorMessage")
here is the code of my lambda function:
/* login and return the jwt token infos and set the auth cookie */
import { ok, internalServerError, unAuthorized } from '../../lib/response.js';
import { login } from '../../lib/token.js';
import { logger } from '../../lib/logger.js';
import { authLambda } from '../../constants/constant.js';
export const handler = async (event) => {
logger.info('START', authLambda.login);
let responseObject;
let date = new Date();
date.setTime(+ date + (86400000)); // 24h
try {
const token = await login(event.body);
if (token) {
let cookie = 'auth='+token
responseObject = ok(cookie);
} else {
responseObject = unAuthorized();
}
logger.info('END => ', authLambda.login, responseObject);
return responseObject;
} catch (e) {
logger.error('ERROR', authLambda.login, e);
return new Error(internalServerError(e));
}
};
So, I have this as the response of the request:
{
"message": "Ok",
"statusCode": 200,
"body": "auth=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImJpbmN6YWttYXJ0aW40QGdtYWlsLmNvbSIsImlkIjoiOTUwNzI1YjAtODJlMy00Nzc0LWIwZDEtMWMxMTcyM2UzMTY3Iiwicm9sZSI6IkVuZ2luZWVyIiwiaWF0IjoxNjcwNDk0NjYzLCJleHAiOjE2NzA1ODEwNjN9.Y7X4AiVV84rCFLvuGTHbcyKMfZhpZuq3iWERzkHRZS0"
}
But I only want to have this:
{
"message": "Ok",
"statusCode": 200
}
Thanks 🙂
Expectation: when wrong login credentials are provided, "non_field_errors: Unable to log in with provided credentials" is returned, such as below (screenshot from a tutorial which I'm following verbatim)
Reality: instead I'm getting the error below.
This gets printed to the console:
POST http://127.0.0.1:8000/api/v1/token/login 400 (Bad Request)
Interestingly I get this same error when I try to create users with passwords that are too short. I'm not having any issues with axios or the server when I provide the right credentials for log in, or use passwords of sufficient length when creating new users. When trying to catch errors such as these that I'm failing to get the expected result.
My code for catching the error is the same as in the tutorial:
methods: {
submitForm() {
axios.defaults.headers.common['Authorization'] = ''
localStorage.removeItem('token')
const formData = {
username: this.username,
password: this.password
}
axios
.post('/api/v1/token/login', formData)
.then(response => {
const token = response.data.auth_token
this.$store.commit('setToken', token)
axios.defaults.headers.common['Authorization'] = 'Token ' + token
localStorage.setItem('token', token)
this.$router.push('/dashboard/my-account')
})
.catch(error => {
if (error.response) {
for (const property in error.response) {
this.errors.push(`${property}: ${error.response.data[property]}`)
}
} else if (error.message) {
this.errors.push('Something went wrong. Please try again!')
}
})
}
}
Is there something in the server settings that I should change?
I'm using Django, rest framework, and djoser.
Don't know if you're using a custom exception handler in Django rest framework but it looks like the issue could be from the way you're handling the error in your frontend application.
You can handle the errors like this.
methods: {
submitForm() {
axios.defaults.headers.common['Authorization'] = ''
localStorage.removeItem('token')
const formData = {
username: this.username,
password: this.password
}
axios
.post('/api/v1/token/login', formData)
.then(response => {
const token = response.data.auth_token
this.$store.commit('setToken', token)
axios.defaults.headers.common['Authorization'] = 'Token ' + token
localStorage.setItem('token', token)
this.$router.push('/dashboard/my-account')
})
.catch(error => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
})
}
Can be found here
I'm new to loopback. I'm trying override response body when model record not found.
this is the default response body from explorer:
{
"error": {
"statusCode": 404,
"name": "Error",
"message": "could not find a model with id 666",
"code": "MODEL_NOT_FOUND",
"stack": "..."
}
}
my expected result:
{
"status": 404,
"message": "could not find a model with id 666"
}
https://loopback.io/doc/en/lb3/Defining-middleware.html#middleware-phases
final - Deal with errors and requests for unknown URLs.
app.middleware('final', function(err, req, res, next) {
if (err && err.code === 'MODEL_NOT_FOUND') {
res.statusCode = 404;
res.json({status: 404, message: err.message});
}else {
next();
}
});
Register the with a file in the boot directory, in a file pointed to by middleware.json, or in server.js.
I'm writing a lambda in node.js that will call an api(post) and gives back the resulting body and the code is as below.
const AWS = require('aws-sdk');
const request = require('request');
exports.handle = function(e, ctx, callback) {
var bodyDetails = {
uri: "myURL",
json: {
"requestChannel": "web1" },
"method": "POST"
};
callback = ctx.done;
var data = e.bodyJson || {};
request(bodyDetails, function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(JSON.parse(JSON.stringify(body)));
jsonBody = JSON.parse(JSON.stringify(body));
console.log(body + "\t from suvccess") // Print the json response
callback(null, jsonBody); // Return the JSON object back to our API call
} else {
callback(error);
}
});
}
and I'm testing the same in my lambda console. by passing a blank json {} and I get back the correct response.
Now my next plan is to integrate this piece against API Gateway. So I've created an api for this in my apigateway and in that, I've created a resource named home. and in the home, I created a GET method. with the below details.
Integration type: Lambda Function
Use Lambda Proxy integration : checked
Lambda Region: us-east-1
Lambda Function: myWorkingLambdaName
when I tested this using the test option given by apigateway. I get the response as
Request: /home
Status: 502
Latency: 2942 ms
Response Body
{
"message": "Internal server error"
}
when I see my console I see the values of the success block printed, but the status code is 502. This is very confusing, please let me know where am I going wrong and how can I fix this.
Thanks
API Gateway expects the following properties to be returned from your Lambda:
{
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"body": "..."
}
So, instead of callback(null, jsonBody), you should be calling callback like this:
callback(null, {
isBase64Encoded: false,
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*",
},
body: JSON.stringify(jsonBody),
})
I am trying to call my web services using AJAX CALL. But i am getting with Unsupported Media Type Error in my firebug tool.
But it works fine in Rest-client Jar. Below is my code.
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:8888/taxi/add/driver", // Location of the service
data: {"firstName":"ttt","lastName":"gggg","gender":null}, //Data sent to server
//contentType: "application/json", // content type sent to server
//dataType: "json", //Expected data format from server
//processdata: true, //True or False
success: function (json) {//On Successfull service call
//shell.loaded();
alert("cross domain ajax success full.");
var result = json.firstName;
//alert("result===" + json.length);
//alert("result===" + json.data.length);
alert("result===" + result);
$("#dvAjax").html(result);
},
error: ServiceFailed// When Service call fails
});
return false;
});
});
function ServiceFailed(xhr) {
alert(xhr.responseText);
//if (xhr.responseText) {
// var err = xhr.responseText;
//if (err)
// error(err);
//else
error({ Message: "Unknown server error." })
//}
return;
}
please point out where is the mistake i have done. Thanks in Advance.
Regards
Karthick
What error you are getting? where does the response comes?? does it goes to success or error you should have specified dataType:'json'