I am trying to get an alert with after sending an email with nodemailer and not just the json response. Here is what I have so far:
app.js (nodejswith nodemailermodule):
transporter.sendMail(mailOptions, (error) => {
if (error) {
res.sendStatus(500)
} else {
res.sendStatus(200)
}
transporter.close();
});
});
angularjs:
$http.post({
url: '/contactUs',
data: '',
}).then(
function successCallback(response) {
$scope.alert("Message Sent!!")
},
function errorCallback(response) {}
)
you'll need to just call alert("Message Sent") instead of $scope.alert("Message Sent").
If you want it to be angularized, you can inject $window and call $window.alert("Message Sent") which will make it easier on you if you're unit testing.
Related
I am trying to use fetch and post methods to change a value. This all works fine. My problem is moving on after the fetch (in this example, I want to post a simple "ok"). The problem is that it never actually gives me that message. It gives me the "error" message, when I change to a wrong API.
async function sendCon(number) {
let data = JSON.stringify(number);
console.log("I accept")
await fetch(acceptAPI, {
method: 'POST',
body: data
}).then(function() {
console.log("ok");
}).catch(function() {
console.log("error");
})
}
Please help, I've been trying to figure this out for three days.
Thanks
You can assign the response to a variable and check if the response has a status code of 200.
async function sendCon(number) {
try {
let data = JSON.stringify(number);
const response = await fetch(acceptAPI, {
method: "POST",
body: data,
});
if (response.status === 200) {
console.log("ok");
} else {
console.log("error");
}
} catch (error) {
console.log(error);
}
}
Is there a way to ignore or bypass this error code 400 and just trigger a function when this error occurs?
I tried this : --
vm.createOrder = function () {
var deferred = $q.defer(); // update
orderService.createOrder()
.then(function (response, status) {
deferred.resolve(response); // update
if(status == 400) {
console.log('Should never happen but trigger a function anyway! ');
localStorage.clear();
}
console.log('Successfully created an order: ', response.status);
})
}
orderService: --
createOrder: function () {
return $http({
url: 'apiURL',
method: 'POST'
})
}
but it doesn't even console.log the string in the if(status) condition or in the success, but the POST method does go through so its posting the data I want to post but it returns an error code of 400.
Edit fixed
orderService.createOrder()
.then(function (response) {
console.log('Successfully created an order: ', response.status);
})
.catch(function (e) {
console.log('Should never happen but trigger a function anyway! ');
localStorage.clear();
console.log(e);
})
Your service should look like this.
createOrder: function () {
return $http.post('SomeURL')
.then(function (response) {
return response.data;
},
function (response) {
return $q.reject(response);
});
}
You should call it like this, rather than a try catch.
orderService.createOrder().then(function(response){
//Successfull Call
},function(response){
//Error on call
});
I am having trouble updating a name in mongodb. The name is first saved by the user in a variable and passed into a function like this: putAjax(editName) Then it goes to the function here:
function putAjax(editName) {
$.ajax({
type: "PUT",
url: "/items/"+ editName,
data: editName,
dataType: 'json',
})
.done(function(result) {
console.log("result:", result);
console.log("data successfully saved:");
})
.fail(function(jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
};
I can console.log(result) and I can see the edited name so I assumed that the edit took place. Finally it makes the call to app.put on the server:
app.put('/items/:name', function(req, res) {
Item.find(req.params.name, function(err, items) {
if (err) {
return res.status(404).json({
message: 'Internal Server Error'
});
}
Item.findOneAndUpdate({
name: req.params.name
}, {
$set: {
name: req.params.name
}
}, { new: true },
function () {
res.json(items);
});
});
});
This is where the update doesn't seem to happen. When I use mongo shell, the one document I have still continues to have the same name and not the edited name. The confusing part is, why does console.log(result) show me the edited name then. I would really appreciate any help on this. Thanks.
You aren't passing a unique key to the database query. You're intention is to change the name stored in the database for an existing record but you're not doing this. Instead you are attempting to find a record that matches the new name value and you always return the value you have sent to the server.
Instead you need to pass a unique identifier with the AJAX request, using the URL makes the most sense.
function putAjax(id, editName) {
var payLoad = { name: editName };
$.ajax({
type: "PUT",
url: "/items/"+ id,
data: payLoad,
dataType: 'json',
})
.done(function(result) {
console.log("result:", result);
console.log("data successfully saved:");
})
.fail(function(jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
};
Server side code:
app.put('/items/:id', function(req, res) {
var data = req.body; // data should be validated
Item.findOneAndUpdate({ _id: req.params.id }
, { $set: data }
, { returnOriginal: false }
, function (err, result) {
if (err) {
return res.status(500).json({
message: 'Internal Server Error.'
});
}
return res.json(result);
}
);
});
When the session is expired, User cant log back in without a page refresh because the _token in ajax headers is expired(AKA TokenMismatchException). I cant handle the exception by redirecting user to a log in page because the login is an overlay modal and the request is handled via ajax.
I thought i could catch the mismatch exception in Handler.php and return a json response with a session token. and on the client side, use the new token to continue the intended process. However, when i use the new token passed from server, the session token will be changed again on server side which results another TokenMismatchException.
So how should i handle the exception in a secured way without refreshing a page?
Here's what i have right now:
setup csrf_token in a global js file:
$(function () {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content') }
});
});
render method in app/exceptions/handler.php:
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else if ($e instanceof TokenMismatchException)
{
if ($request->ajax()) {
return response()->json([
'message' => 'TokenMismatchException',
'token' => csrf_token()
]);
}
}
else
{
return parent::render($request, $e);
}
}
in authentication.js:
$.ajax({
type: "POST",
url: "/auth/login",
data: {
"email" : $('#login_email').val(),
"password" : $('#login_password').val(),
'remember': $('#login_remember').is(':checked')
},
success: function(response) {
if (response.message === 'TokenMismatchException') {
console.log(response); //message and token exist
//if catch the exception, use the new token to set up the ajax headers and login again
$.ajaxSettings.headers["X-CSRF-TOKEN"] = response.token;
console.log($.ajaxSettings.headers["X-CSRF-TOKEN"]);
$.ajax({
type: "POST",
url: "/auth/login",
data: {
"email" : $('#login_email').val(),
"password" : $('#login_password').val(),
'remember': $('#login_remember').is(':checked'),
},
success: function(res) {
console.log(res);
},
error: function(err) {
console.log(err);
}
});
}
console.log('logged in');
},
error: function(xhr, status, err) {
}
});
thanks in advance.
In your render function, you've to check for a specific TokenMismatchException. So may be you can try something like this:
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return response()->json('msg', 'Your session has expired. Please try again.');
}
You may also pass a new csrf_token along with the json so that you can replace the old one with the new one and send the form request again.
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return response()->json(['msg'=> 'Your session has expired. Please try again.', 'token'=> csrf_token()]);
}
I haven't tested this code. But this should get you started.
Also, if you want, you can use a package: https://github.com/GeneaLabs/laravel-caffeine
I am trying to implement angular resource for login like this
var data = new Login({
username: user.userName,
password: user.password
})
data.$save()
This is suppose to return some data to me if login is successful or return error if it is not.
What I want is the callback like the angular http post method like this .
data = JSON.stringify({
username: user.userName,
password: user.password
})
$http.post('API/sigin',data,
{
headers: {
'Content-Type': 'application/json'
}
}
)
.success(
function(response){
// success callback
console.log("doing sign in");
},
function(error){
// failure callback
return error
}
)
I switched to resource when http post failed me. It will just just hang perpetually and will later return error.
I am using angular 1.4.3.
any help, info will be appreciated
..factory.js
//Create a factory for the Login API
angular.module(...)
.factory('LoginEntity', ['$resource', function ($resource) {
return $resource(
'API/sigin',
{
save: {method: 'POST'},
update: {method: 'PUT'}
}
);
}])
...controller.js
angular.module(...)
.controller('xxxController', ['LoginEntity', function(LoginEntity){
//in Controller add LoginEntity dependency
LoginEntity.save({
username: user.userName,
password: user.password
},
function (response) {
//success callback
},
function () {
//error callback
//usually do some logging stuff here
});
}]);