How to map URL in iron-ajax call to server with that of routes in server-side index.js? - ajax

<iron-ajax id="ajax_call_send_student_feedback" url="/student/feedback" handle-as="json" content-type='application/json' method="POST" body="{{student_feedback_body}}" on-response="ajax_response_student_feedback" on-error="ajax_error_student-feedback"></iron-ajax>
The above is my ajax-call to post body to server.As am running locally my url when this call is made is localhost:3000/student/feedback.
On the server-side , I have this following route to take care of the above ajax-call
app.post('/student/feedback',function(req, res) {
var body = _.pick(req.body, 'student_loginID', 'student_feedback_subject', 'student_feedback_message');
res.json(body);
});
But as soon as I make the ajax call , following error is shown on client-side.
POST http://localhost:3000/student/feedback 400 (Bad Request)
I have already checked the API end-point via Postman. So , there is some problem in the URL which I am not getting.
Ask for any other information , if I haven't provided.

this is probably a problem with your server route. inspect what's being sent to the server and how you're modifying that data.
log the value of body before your response returns json
send back a piece of hard-coded json
app.post('/student/feedback',function(req, res) {
var body = _.pick(req.body, 'student_loginID', 'student_feedback_subject', 'student_feedback_message');
console.log(body)
res.json({"foo": "bar"});
});

Related

Can you access the req object in the cy.route method before returning the stubbed data?

I am looking to get the req object in the cypress route method. By doing so I could decide what the user gets back when hitting the graphql route which has dynamic responses. Has anyone be able to accomplished this?
I think having access to this would be incredibly useful.
I hope this helps, where xhr.requestBody does help in accessing the request body,
cy.route("GET", "/login").as("getLogin");
cy.get("#contactID").type("email#gmail.com");
cy.contains("Login").click();
cy.wait("#getLogin").then(function(xhr) {
// we can now access the low level xhr
// that contains the request body,
// response body, status, etc
const request = xhr.requestBody;
expect(response[0]).to.have.property("SomeKey", "Data");
const response = xhr.responseBody;
expect(response[0]).to.have.property("LineName", "Line A");
});

springsecurity: using CSRF token obtained from CrossOrigin REST service to POST data

I have this REST service on domainA:
#CrossOrigin(origins={"http://domainB"})
#RequestMapping(value="/csrf", method=RequestMethod.GET)
public #ResponseBody
CsrfToken getCsrfToken(HttpServletRequest request) {
CsrfToken token = (CsrfToken)request.getAttribute(CsrfToken.class.getName());
return token;
}
Then I want to obtain CSRF token from above service (by using javascript on domainB) and add it to a <form action="http://domainA> on domainB and send this form to domainA (it is a simple form that has a submit button).
The problem is I get HTTP Status 403 – Forbidden.
As the opposite: when I manually set the _csrf value (obtained manually in the other browser tab pointing to domainA/csrf) in the <form action="http://domainA> and submit it then it works.
The difference which I noticed is that when I manually refresh browser's tab domainA/csrf then I get constantly the same value (and this value works), but when the domainA/csrf is obtained by the javascript from the domainB it is each time different and when using it - it does not work.
Can anyone help?
domainA: www.fridayweekend.com/rest/csrf
domainB: www.friwee.com/register (hit F12 and observe what call to www.fridayweekend.com/rest/csrf returns....)
As #dur said - the problem was in the JavaScript code. I used:
$.getJSON(domainA/csrf, callback)
which was ending up each time with a new session and a new CSRF token for it.
The solution was to use cors_ajax_call function except $.getJSON, defined as below:
var cors_ajax_call = function(address, callback){
$.ajax({
url: address,
context: document.body,
xhrFields: {
withCredentials: true
}
}).success(callback);
}
Thank you for your input! Hope this help someone :)

Laravel cannot access FormData from an HTTP POST request?

I'm having trouble getting values from my request when I set the content-type as multipart/form-data, but when I set the content-type as application/x-www-form-urlencoded everything works as expected. The values seem empty.
The request I sent via Postman:
Laravel API snippet:
use Illuminate\Http\Request;
...
public function foo(Request $req){
echo $req->get('some_key');
}
I've tried extracting the values via $req->get('key_name'), $req->key_name but to no avail. Calling the $req->all() method gives me the array with correct content but I have trouble extracting the values from it as well, is there a simpler way to achieve this? Thanks in advance.
When using multipart/form-data, set the action to PUT or PATCH and be sure to use the FormData object client side:
let Data = new FormData();
// using vuejs as an example of appending files.
Data.append( 'your_file', this.$refs.input.files[0], this.$refs.input.files[0].name );
Data.append('_method', 'PATCH');
axios.post('/api/foo', Data ).then( Response => {
// handle success
});

Datatables 1.10.5 ajax error handler - Getting access to the http status code

I'm using Datatables 1.10.5 and I have the ajax error handler defined. I need to gain access to the actual http status code when the error fires so I can see if my user's session time has expired (HTTP 401) vs if there's something wrong on the backend such as an HTTP 500 error. Right now the techNote is always 7.
How can I get that elusive HTTP status code from the ajax transaction? I tried below, but it does not fire.
$("#example").ajaxError(function(event, jqxhr, request, settings){
alert("Failure HTTP Code:"+jqxhr.status);
});
and
$.fn.dataTable.ext.errMode = 'throw';
$('#example').on('error.dt', function(e, settings, techNote, message) {
console.log( 'An error has been reported by DataTables: ', message);
});
Does not have the information I need, or at least that I cannot find it in any of the passed variables.
I've been able to get access to the status code without overriding global jQuery ajaxError by overriding the more specific to DataTables $.fn.dataTable.ext.errMode with a function:
$.fn.dataTable.ext.errMode = function (settings, tn, msg) {
if (settings && settings.jqXHR && settings.jqXHR.status == 401) {
window.location = window.location.origin + '/login';
return
}
alert(msg) // Alert for all other error types; default DataTables behavior
};
This example shows a redirect to login on 401 status code, however, you could do the same with any other status code.
Last note is you might want to leverage the DataTables statusCode option for status code specific handling but you'll still need to override $.fn.dataTable.ext.errMode if you want to bypass default error handling since it executes before anything you define in statusCode
Handle xhr event. When Ajax error occurs third argument json would be null and fourth argument xhr would contain jQuery XHR object. You can get the status by accessing xhr.status property.
Also see $.fn.dataTable.ext.errMode which could be used to instruct DataTables not to show the alert.

Debugging Ajax requests in a Symfony environment

Not sure if SFDebug is any help in this situation. I am making an ajax post using jQuery. Which retrieves JSON data in my action URL and then makes a call to the Model method that executes the action. The part until my action URL, and the jQuery call to it work fine. With the data transmitted from the client to the server well received and no errors being made.
It is the part where it calls the method on the Model that is failing. My jQuery method looks like this:
$.post(url, jsonData, function(servermsg) { console.log(servermsg); }) ;
My server action is like this
public function executeMyAjaxRequest(sfWebRequest $request)
{
if($request->isXmlHttpRequest())
{
// process whatever
$servermsg = Doctrine_Core::getTable('table')->addDataToTable($dataArray);
return $this->renderText($servermsg);
}
return false;
}
The method of concern in the Table.class.php file looks like this:
public function addDataToTable($dataArray)
{
// process $dataArray and retrieve the necessary data
$data = new Data();
$data->field = $dataArray['field'];
.
.
.
$data->save();
return $data->id ;
}
The method fails up here in the model, when renderText in the action is returned and logged into the console, it returns the HTMl for SFDEBUG. Which indicates that it failed.
If this was not an Ajax call, I could debug it by seeing what the model method spat out, but this is a little tedious with Ajax in the mix.
Not looking for exact answers here, but more on how I can approach debugging ajax requests in a symfony environment, so if there are suggestions on how I can debug this, that would be great.
You must send cookie with session ide key via ajax
(Assuming you have XDEBUG configured on the server)
In order to trigger a debug session by an AJAX request you have to somehow make that request to send additional URL parameter XDEBUG_SESSION_START=1. For your example:
$.post(url + '?XDEBUG_SESSION_START=1', jsonData, function(servermsg) { console.log(servermsg); }) ;
You can also trigger it via cookie, but appending URL parameter usually easier.

Resources