I have an express application with many routes that work fine but today I tried to add a new route and it just seems to no never get hit. I tried with a request from another application of mine and through Postman. Both return just Internal Server Error. However, every other one of my routes work just fine.
For the query in question test is a tinyint(1) and id is an int
Here is the route in question in my User.js route.
router.put("/add/:id", function (req, res, next) {
db.query(
"UPDATE user SET test = ? WHERE id = ?",
[1, req.params.id],
function (error, response) {
if (error) throw error;
if (response.affectedRows > 0) {
res.sendStatus(200);
} else {
res.sendStatus(500);
}
}
)
});
My postman request:
PUT http://localhost:3000/user/add/39583
Notthing gets hit though, I tried switching out put for post and I tried adding logging within the route but nothing shows. Not even the status is returned, it just says Internal Server Error in Postman
Related
So Am unable to make a search function i want to get a variable from search field and show the results that matched but am constantly getting this error
variable undefined when i try to console.log it in the node server
Edit-- i have already changed the axios.post to axios.get
app.get(`/search/`, (req, res) => {
let {name} =req.body
var Desc = name
console.log(name)
var Op= Desc+'%'
const q = "SELECT * FROM taric where Description LIKE ? ";
con.query(q,[Op], (err, search) => {
if (err) {
console.log(err);
return res.json(err);
}
console.log(search);
return res.json(search);
});
});
As you can see you are making POST request from frontend where as there is no POST request route to handle your request. As you have make route of GET for fetching the data from backend you need to make GET request from frontend as well. So you need to do as below:
axios.get(`your_endpoint_route_goes_here`);
instead of this:
axios.post(`your_endpoint_route_goes_here`, requestBodyObj);
HTTP methods are not the same.
You are using app.get in the server while triggering a POST call from your client.
axios.post <-----> app.get
(There is no route for POST call which client is expecting)
Within my Posts routes, i'm making it so that the user can go to posts/:id to retrieve information about the post with that ID, however i'm trying to make sure that if the user goes to a post that doesn't exist, he gets redirected back to the posts index route. My issue is that the server is going through the entire router.get function instead of redirecting the user and stopping.
router.get("/:id", async (req, res) => {
if (!mongoose.isValidObjectId(req.params.id)) {
console.log("Test1")
res.redirect("/")
res.end()
}
console.log("Test2")
try {
console.log("Test3")
const post = await Post.findById(req.params.id)
if (post == null) res.redirect("/")
res.render("posts/show", { post: post })
}
catch {
console.log("Test4")
res.redirect("posts/index")
res.end()
}
})
If I go to the route posts/weiqeiqwie (which isn't valid) it prints all of the test console logs. What can I do for the code to return after the error?
I'm still a bit new to using express, so sorry for the dumb question.
you cant redirect AND render at the same time.
this is what this part of the code does when post is null :
if (post == null) res.redirect("/")
res.render("posts/show", { post: post })
adapt it like this, so that now when post is null it only does the redirect part.
(never forget the return)
if (post == null) return res.redirect("/");
res.render("posts/show", { post: post })
the same goes for the redirect line 3 :
it should be :
if (!mongoose.isValidObjectId(req.params.id)) {
console.log("Test1")
return res.redirect("/")
}
also res.end() is not required. you can remove it from everywhere.
I am trying to create a Weather API using node. In my controller file, I have this code which is run for the /check route.
controller.js:
//Check Weather
exports.check = (req, res) => {
UserModel.check(req.body.city)
};
model.js:
//Check Weather
function getData(city) {
url = "something";
request(url, function (err, response, body) {
if(err){
console.log('error:', error);
} else {
console.log('body:', body);
}
});
}
exports.check = (city) => {
city = city.toLowerCase();
let values = getData(city);
console.log(city);
return(values);
};
route:
app.post('/check', [
UsersController.check
]);
When I run this, it functions properly and the correct thing is logged in the console. However, after I send a request in Postman and the console.log shows up, Postman seems to be hung up as seen in this pic. Is there anyway I can make it so that Postman stops sending the request after return or console.log?
Postman is waiting for a response from the server. Your code is not currently sending any response, so postman seems 'hung up' as it is waiting. Try changing the line saying UserModel.check(req.body.city) to say res.send(UserModel.check(req.body.city)) so it will send the data returned from your UserModel.check function back as the response. Alternatively, if you don't want to send back the returned value, you could just add res.send(PutWhateverYouWantSentHere) after the function call.
I'm trying to get a simple example working with the MEAN stack and I noticed that my DELETE request does not work in Firefox. I believe this is due to CORS.
When i click a link to submit a DELETE request with angularJS to my ExpressJS backend, I see that a GET request is first called, and then the actual DELETE request is called, but the DELETE request never finishes.
This all seems to work in Chrome no problem. No unexpected GET request called, and the DELETE request actually finishes. How can I make this work in Firefox?
Express section for cors:
// CORS Stuff in app.js
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Content-Length");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
if(req.method == 'OPTIONS') {
res.send(204);
//next();
} else {
next();
}
//res.send(200);
});
app.get('/notes', note.get(db));
app.post('/notes', note.create(db));
app.put('/notes/:id', note.update(db));
app.delete('/notes/:id', note.delete(db));
Then i have this note.js file
exports.delete = function(db) {
return function(req, res) {
console.log('were in delete middleware');
//var note_id = req.body.id;
var note_id = req.params.id;
console.log("note_id = "+note_id);
var collection = db.get('notes');
collection.remove(
{_id: note_id}
),
function(err, doc) {
console.log('were in delete middleware function');
// If it failed, return error
if (err) {
console.log('were in delete error');
res.send("There was a problem deleting that note from the database.");
} else {
console.log('were in delete success');
res.send(200);
}
}
}
}
My browser url is http://localhost:63342/express_example/public/#/
Update
My server responds to the preflight request with this:
Server console:
OPTIONS /notes/53568807130e0f701f000001 200 0ms - 2b
GET /notes 304 8ms
Browser console:
So this is not a problem with CORS, you have a small logic error in your code.
The problem is with this call:
collection.remove(
{_id: note_id}
),
I'm going to assume that it expects a second parameter which is a callback function, which is probably why you ended the statement with a , and not a ;. Also you define the callback function as the next statement but never use it. Hence why the delete never ends, the callback is never called because it wasn't passed in to the collection.remove() call.
Try this instead:
var collection = db.get('notes');
collection.remove(
{_id: note_id},
function(err, doc) {
console.log('were in delete middleware function');
// If it failed, return error
if (err) {
console.log('were in delete error');
res.send("There was a problem deleting that note from the database.");
} else {
console.log('were in delete success');
res.send(200);
}
});
Not sure why this would work for Chrome and not for firefox, but if it had to guess it would be that Chrome might be getting the 204 back from your CORS handler and just be accepting it. Thats just a guess though because the code you posted above will never return a response back to a client.
You probably shouldn't auto-reply with a 204 response unless your Express handlers have actually deleted the object. You didn't post your handlers here, but with Mongoose/MongoDB it might look like:
app.delete('/records/:recordId', function(req, res){
req.record.remove(function(err){
if (err) {
console.log("Error deleting record");
return res.json(500, {error: err});
}
return res.json(204);
});
});
The problem with what you are doing is that it opens your server to requests from all domains. The reason it was failing before is if you notice the request header has a host of localhost: 3000 but your server is only accepting requests from localhost: 63342
You probably don't need to worry about opening it up to all domains unless you are worried about someone else making an application that is hitting your server that will be running on client computers. Anyone can hit the server using fiddler or any REST client like Advanced REST Client.
The following code is the user-facing part of a new node app we are building:
var loadInvoice = function(req, res, next) {
Invoice.findById(req.params.invoiceId, function (err, invoice) {
if (err) {
res.send(404, 'Page not found');
} else {
req.invoice = invoice;
next();
}
});
};
app.namespace('/invoices/:invoiceId', loadInvoice, function () {
app.get('', function(req, res){
var templateVals = {
//some template data
};
res.render('paymentselection', templateVals);
});
app.post('', function(req, res){
var data = {
// some data for the apiCall
};
someAPI.someRequest(data, function(err, data) {
console.log(res.status());
res.redirect(data.url);
});
});
});
The first method returns a confirmation page where the user presses a button to post to the same url, which triggers a redirect to an external website.
This all works exactly once. Every second request will crash the app with the message Cant set headers after they are sent. After carefull inspection of the code I could find no reason for this to happen so I added the console.log line which indeed confirms the location header has been set. But it is set to the value i got from someAPI on the previous request not the current one.
This makes absolutely no sense to me. I do not store this value anywhere nor do I do caching or persistence of this data in any way.
Does anybody know what could be causing this?
I use express, express-namespace, mogoose and swig
I found out the problem was being caused bij the 'Restler' libaray used within 'someAPI'. I have no idea how this is possible but swapping it out with something else fixed the problem.