I am posting to the /update route.
This works because I can see my console.log() items printing in the terminal, see here:
However, my code seems to be totally ignoring the find one and update function.
All I want to do is run a put request to the route and have it update the post.
Here is my AJAX request:
$.ajax({
url: "/admin-panel/update/",
method: "PUT",
data: $data,
success: function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
window.location.href = "/admin-panel/update/";
},
error: function(err) {
if (err) throw err;
}
});
And here is the put request handler in the backend:
router.put("/:action", function(req, res, next) {
if (req.params.action.toLowerCase() == "update") {
console.log("started")
var timelineItems = require("../schemas/timelineItems.js");
console.log("timeline items model inserted:", timelineItems)
timelineItems.findOneAndUpdate({_id: req.body.id}, function (err, post) {
if (err) {
next(err);
}
console.log("post:", post)
res.send("item updated!");
});
console.log("should be done");
} else {
var err = new Error('Access forbidden, please login!');
err.status = 403;
next(err);
}
});
I know that the right data is being run in the put request also as I checked the value of $data on the view and req.body on the backend too, so I am unsure why this isnt working.
your findOneAndUpdate query missing update parameter.
Model.findOneAndUpdate([conditions], [update], [options], [callback])
Check this doc
Related
I'm not sure whether what I did is the right way to implement or not.
Here is what I have tried, I'm making a GET request to fetch data from Google and then I need to send data to my Server via POST request.
When I'm making the post request I'm getting the below error:
connect ECONNREFUSED 127.0.0.1:443
Code in NodeJS
request({
url: 'https://people.googleapis.com/v1/people/me?requestMask.includeField=person.photos,person.emailAddresses,person.names',
auth: {
'bearer': access_token
}
}, function(err, response) {
if(err)
{
res.status(500).send({ error: " Info error", data: null, message: "Error" });
res.end();
}
else
{
var res_data = JSON.parse(response.body);
var username = res_data.names[0].displayName;
var userid = res_data.names[0].metadata.source.id;
var data = {name: username,id:userid};
postToApp(data, (postResponse) => {
//respond back with the result/error to your API
console.log(postResponse);
});
}
});
postToApp Function
function postToApp(data, callback) {
var options = {
url : 'https://localhost/:3333/saveInfo',
method : 'POST',
body : data,
json : true
};
request(options, function (error, response, body) {
console.log(error + response + body);
if (!error && response.statusCode == 200) {
console.log(body);
callback(body) // call the function back with the data you want to process;
} else {
console.log('Error from server is' + error);
callback(error) // call the function back with error to process;
}
});
}
I'm trying to get the results pulled from the API inserted into a database. It returns a SQL error when the program is run. It seems I'm not having this sent in the right syntax and I cant seem to to get it to do so. Is there a better way to do this?
var request = require('request');
var mysql = require('mysql');
var replace = require ('Regexp')
var url = 'https://api.nicehash.com/api?method=stats.provider.workers&addr=3Hwm6i8aefzHhJTbEGtSJeR6tZCJXqY7EN';
//connect to database
var con = mysql.createConnection({
host: 'localhost',
user: 'xxxxx',
password: 'xxxxx',
database: 'xxxxx',
table: 'workerstats'
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
const requestHandler = (request, response) => {
response.end(workerstats)
}
request.get({
url: url,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
}
else if (res.statusCode !== 200)
{
console.log('Status:', res.statusCode);
}
else {(!err && data && data.result && data.result.workers)
var workerstats = JSON.stringify(data.result.workers);
var wsclean = workerstats.replace(/[&\/\\#+()$~%'*?<>{}]/g,'')
.replace(/"a":/g,'');
};
console.log(wsclean);
var sql = "INSERT INTO 'workerstats' (workers, accepted, uptime, xnsub, difficulty, zone, algo) ?", wsclean;
con.query(sql, [workerstats], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
}
);
})
EDIT: Okay so after hours of tinkering, I 'think' I've made progress, but that silly A: has got me again. Its viewing as an object, and SQL is rejecting it. Though I thought (Though obviously improperly) I converted it to string. This is the amended code. Please forgive the formatting, it wasnt playing nice.
request.get({
url: url,
json: true,
headers: { 'User-Agent': 'request' }
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
}
else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
}
else {
(!err && data && data.result)
var data = JSON.parse(data.result);
var responseJson = JSON.stringify(data.response);
var query = connection.query('INSERT INTO table SET column=?', responseJson, function (err, result) {
if (err) throw err;
console.log('data inserted');
});
}
});
It returns the following error:
undefined:1
[object Object]
SyntaxError: unexpected token o in JSON at postion 1
Awesome. So somewhere I did something stupid, or improperly. In the raw API that object Object appears like: {"a":"158.01"} - How do I convert that to a string, when I thought I already did? Id also like to eliminate the 'a' and the ':' entirely as im not sure how to process that into SQL and its unneeded information.
When you setup json: true in the request option, You no longer have to perform JSON.parse(data.result), you directly access the data as object. Therefore the error, because JSON.parse({ a: 1}) call the toString method, and the result [object Object] its not valid JSON.
Note: You convert the data.result.workers to a string. I think you should leave it as an array for it to work.
con.query(sql, data.result.workers, function (err, result)
I am registering a user and after successful registration I want alert something in client side. So, what I do in server side, after registration I'm sending a value "registered" then when it gets that value, my client side would know that user is registred but I don't know how to get that value in my client side.
router.post('/registration', function (req, res, next) {
var stud = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
admin: 0
};
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('user-data').insertOne(stud, function (err, result) {
assert.equal(null, err);
console.log('Student inserted');
db.close();
res.json('registred');
})
})
});
My client side code
$('.MyForm').on('submit', function(event){
event.preventDefault();
$.ajax({
url: '/registration',
method: 'post',
success: function(response){
}
})
});
There is not very much because I don't know what to do next
All you still need to do is put the alert in the callback to the ajax request
success: function(response) {
alert('User registration succeeded!')
}
Since you're using HTTP protocol, why not use its cohesive response codes to indicate which action has happened? For example:
200 - user successfully created
400 - malformed input data
409 - one of unique user's model field has been already taken
And so on. Use method 'status' on response object to set appropriate return code. I assume that you are trying to create server with REST's rules in mind, therefore your endpoint should return freshly created entity on POST request.
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('user-data').insertOne(stud, function (err, result) {
if(err) {
/* At this point, you may decide to check what error has been returned to decide which code will be returned*/
return res.status(400).json(err);
}
console.log('Student inserted');
db.close();
res.status(200).json(result);
})
})
On client side, code might be much more pleasant to eye after you would refactor it to use jQuery's ( since ver. 1.5.1 )'Promise API'
$.ajax({
url: 'http://localhost:8000',
method: 'POST'
})
.done(function( data ) {
})
.fail(function (reason) {
})
my problem is that I'm trying to send some posts requests in an angular loop.
This is my angular code:
for (var i = 0; i < response.length;i++) {
response[i].pedido_id = $scope.pedidos.pedidoSeleccionado;
PedidoDetalleFactory.save(
{
obraId: obra._id,
pedidoId: response[i].pedido_id
},
response[i],
function (result) {
pedidosTransferidos++;
},
function (result) {
// Handle error
}
);
}
And this is my node.js code
.post(Verify.verifyOrdinaryUser, function (req, res, next) {
Servicios.findById(req.body.servicio_id).exec(function (err, servicio) {
if (err) next(err);
req.body.price = servicio.price;
req.body.pedido_id = req.params.pedidoId;
PedidoDetalles.create(
req.body,
function (err, pedido_detalle) {
if (err) next(err);
res.json(pedido_detalle);
}
);
});
});
Everything looks fine, but I get this error
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
Could this be happening beacause angular sends the request too fast to the server?
Please, help
it seem that you set header again after you had response to client. maybe you can try if (err) {return next(err)}, if error, please return, and don't exec the other codes.
I was fetching some results in my server and then I was sending back a json with a attribute "_id" so mongoose was saying "This item already exists", but I couldn't debug the code because I had if (err) next(err); instead of if (err) {return next(err);}
I seem to be having issues performing HTTP Put requests inside an array in AngularJS and ExpressJS. The issue is, when I call the HTTP Put the first time, everything works correctly. However, when I try to call a second time, it doesn't work. The following is my attempt:
When I click a button, I call perform the following HTTP Put Request:
$scope.currentUser.eventsAttending.push(event.eventName);
$http.put('/api/users/' + $scope.currentUser._id, $scope.currentUser)
.success(function(data){
console.log("Success. User " + $scope.currentUser.name);
});
Here is my User schema/model in User.model.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user.model');
var UserSchema = new Schema({
name: String,
...
eventsAttending: [{ type: String, ref: 'Event'}]
});
I route the HTTP Put Request as so in index.js:
router.put('/:id', controller.update);
And here is my actual HTTP Put function called controller.update in User.controller.js:
// Updates an existing event in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
User.findById(req.params.id, function (err, user) {
if (err) { return handleError(err); }
if(!user) { return res.send(404); }
var updated = _.merge(user, req.body);
updated.markModified('eventsAttending');
updated.save(function (err) {
if (err) { return handleError(err);}
return res.json(200, user);
});
});
};
...
function handleError(res, err) {
console.log("Error: ", err);
return res.send(500, err);
}
On the second time where I try to call the HTTP Put function (exports.update above), I always get an error in Mongoose that says:
TypeError: Object VersionError: No matching document found. has no method 'send'
at handleError (/Users/schan/test/go-v2/server/api/user/user.controller.js:131:14)
at Promise.<anonymous> (/Users/schan/test/go-v2/server/api/user/user.controller.js:43:25)
The error is basically where I call the if(err) return { handleError(err); } in the HTTP Put function and when I print out the error, I get Error undefined. I'm honestly unsure on how to debug this or what I may be doing wrong. Can anyone point me in the right direction? If so that would be great! Thanks.
You're not passing res to handleError(). Change instances of handleError(err); to handleError(res, err);