I'm trying to pass some parameters through the URL, i tried to do it this way but it isn't working, the "get(\users:id)" is probably the mistake but i'm not sure whats the correct way:
$.ajax({
type: 'GET',
URL: "'../users/"+id+"'",
success: function(data) {
console.log("success");
}
})
and then i use this route:
app.get('/users/:id', function(req, res) {});
shouldn't this work?
Try this way:
$.ajax({
type: 'GET', URL: "'../users/"+id+"'",
success: function(data) {
console.log("success");
}
}):
An then the route should be:
app.get("/users/:id", function (req, res) {
var id = req.params.id;
});
Your problem seems to be attempting to hit a file system relative path from your client, and the fact that there is no response being sent from your endpoint. Try this (using fetch which is the newer way instead of $.ajax):
fetch('/users/' + id)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
And in your server:
app.get('/users/:id', function(req, res) {
console.log(req.params); // this should be an object containing an `id` param
res.send({});
});
Related
I'm bit stuck here. My intent is to first get all files (filenames) from a static folder + subfolders and list all on front-end.
When user clicks one of the filenames (mostly pdf's), the server returns the selected items content.
I'm able to send the pdf data as binary to front-end, but how could I display the data in a new tab with js/jQuery?
so far..
Server.js -
// Importing and initializing npm/node plugins
var app = require('express')();
var server = require('http').createServer(app);
var logger = require('morgan');
var bodyParser = require('body-parser');
var pdf = require('express-pdf');
var cors = require('cors');
var fs = require('fs');
// Import config settings
var config = require('./config.json');
app.use(logger('dev'));
// Allow application/x-www-form-urlencoded and application/json
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json({
limit: '50mb'
}));
app.use(cors());
app.use(pdf);
app.get('/getfiles', function (req, res) {
var dir = config.sourceDir;
var foundFiles = [];
fs.readdir(dir, function (err, files) {
if (err) {
console.log('Error reading ' + dir);
process.exit(1);
}
console.log('Listing files in Directory ' + dir);
files.forEach(function (f) {
foundFiles.push(f);
});
res.json(foundFiles);
});
});
app.post('/showfiles', function (req, res) {
var file = req.body.filename;
var dir = config.sourceDir;
fs.readFile(dir + file, function (err, data) {
res.contentType('application/pdf');
res.send(data);
});
});
// Open server in port
server.listen(config.port, function () {
console.log('Server listening on port: ' + config.port);
});
module.exports = app;
On front-end -
$(function () {
getFiles();
});
function getFiles() {
$.ajax({
type: "GET",
url: "http://localhost:3000/getfiles",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
if (data) {
$.each(data, function (index, value) {
$("#listContainer1").append("<li><a href='#' onclick='showFile(this)'>" + value + "</a></li>");
});
}
},
error: function (jqXHR, status) {
console.log("Error fetching data");
}
});
}
function showFile(file) {
$.ajax({
type: "POST",
data: JSON.stringify({
"filename": $(file).text()
}),
url: "http://localhost:3000/showfiles",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "application/pdf",
success: function (data, status, jqXHR) {
if (data) {
var file = new Blob([data], {
type: 'application/pdf'
});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
},
error: function (jqXHR, status) {
console.log("Error showing file");
}
});
}
But this keeps falling into the "Error showing file" pit. :(
EDIT:
The first error was corrected by removing the "application/pdf" from post, but now its opening an empty pdf with correct page limit
On the server, change the file fetch code to this:
app.get('/showfiles/:filename', function (req, res) {
var options = {
root: config.sourceDir
};
var fileName = req.params.filename;
res.sendFile(fileName, options, function (err) {
if (err) {
// Handle error
} else {
// Handle success
}
});
});
So I switched the method to GET and used the built-in sendFile method in Express. Then on the front end it's much easier. You can get rid of the showFile function and just update the getFiles function:
function getFiles() {
$.ajax({
type: "GET",
url: "http://localhost:3000/getfiles",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
if (data) {
$.each(data, function (index, value) {
$("#listContainer1").append('<li>' + value + '</li>');
});
}
},
error: function (jqXHR, status) {
console.log("Error fetching data");
}
});
}
Code has not been tested and most likely has mistakes, but should give you a gist of another way you can tackle the problem.
I'm trying to figure out Node.js to use as an api to do GET, POST, etc. I've been stuck trying to figure out why this post is not working.
My ajax call:
$.ajax({
method: "POST",
contentType: 'application/json',
dataType: 'json',
url: "localhost:8000/login",
data: JSON.stringify({user:"john", pass:"123"}),
error: function () {
alert('error');
},
success: function (data) {
alert('success');
}
});
In my express:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/login', function (req, res) {
var user = req.body.user;
var password = req.body.pass;
if(user == 'john' && password == '123') {
res.status(200);
} else {
res.status(401);
}
});
app.listen(8000, function () {
console.log('Example app listening on port 8000!');
});
Any help is greatly appreciated.
you should return some response from your express code, also response should be ended especially in case of just sending only the status code like res.status(401);
app.post('/login', function (req, res) {
var user = req.body.user;
var password = req.body.pass;
if(user == 'john' && password == '123') {
res.status(200).json({t:1});
} else {
res.status(401);
}
res.end();
});
This work for me:
$.ajax({
type: "POST",
contentType: 'application/json',
dataType: 'json',
url: "/login",
data: JSON.stringify({user:"john", pass:"123"}),
error: function (err) {
console.log(err);
alert('error');
},
success: function (data) {
alert('success');
}
});
app.post('/login', function (req, res, next) {
var user = req.body.user;
var password = req.body.pass;
if(user == 'john' && password == '123') {
res.status(200).json({s: 1});
} else {
res.status(401).json({e: 2});
}
});
var json = JSON.stringify({user:"john", pass:"123"});
$.ajax({
dataType: 'json',
type: "POST",
url: "/login",
data: json
}).done(function(data){
console.log("works fine");
});
Should work for an Ajax post function, sending the data to the node server.
The url needs to match the url of the app.post in the node server file, you don't need localhost in front of it.
ContentType is also not necessary and I made the json object outside of the Ajax call instead of setting it inside the Ajax call.
var express = require('express');
var parser = require('body-parser');
var app = express();
var port = 8000;
app.use(parser.urlencoded({extended: false}));
app.use(parser.json());
app.use(express.static('public'));
app.post('/login', function (req, res) {
var user = req.body.user;
var password = req.body.pass;
if(user == "john" && password == "123") {
res.status(200);
} else {
res.status(401);
}
});
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port);
});
And that should work for the node server itself.
I set the server running, so you can always keep track of what port it's listening on, so you don't need to bother scrolling down to change the port, just change the port at the top of your file.
Further the /login was looking fine to me.
Also, I edited the app.use statements and added an extra one.
I think you have to parse request to JSON.
your code is:-
$.ajax({
method: "POST",
contentType: 'application/json',
dataType: 'json',
url: "localhost:8000/login",
//here you used JSON.stringify and on server side you have to parse it to use 'user' and 'pass' as a key of json
data: JSON.stringify({user:"john", pass:"123"}),
error: function () {
alert('error');
},
success: function (data) {
alert('success');
}
});
on the server side
<br>
app.post('/login', function (req, res) {
//parse data to JSON for further use
var dataObj = JSON.parse(req.body.data);
if(dataObj.user == 'john' && dataObj.password == '123') {
res.status(200);
} else {
res.status(401);
}
});
I'm currently having a hard time on using queries within my MEAN App.
In Detail, I'm trying to get the data matching to the input in a search field:
$scope.searchInput = function(search){
$http({
method: 'GET',
url: '/search',
params: {'licensor.name' : search}
})
.success(
function(success){
console.log(success)
})
.error(
function(error){
console.log(error)
});
}
On the server side my code looks like this:
app.get('/search', function(req,res){
ImportCollection.find(function(err, imports){
if(err) throw err
res.json(imports)
});
});
This allways returns the full collection.
Any ideas?
please pass your query with find function, your request will have some query parameter if you are passing the parameter.
for example -
app.get('/search', function(req,res){
ImportCollection.find(req.query).exce(function(err, imports){
if(err) throw err
res.json(imports)
});
});
Thanks
Hey im currently working on my first real webpage using node.js
Im using Express, ejs for layout and redis as database. Im trying to send an ajax call from my index page through my client to my server, use the ajax-call there and pass the final json back to my client where i try to render it on the next ejs page.
Ajax:
$(function(){
$(".search").click(function() {
$.ajax({
method: "POST",
url: "/search",
cache: false,
data: {ort: "hierundda", activity: "Wandern", datum: "01.09.2015"},
dataType: "json",
success: function(data){
alert('Success!')
}
, error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err)
}
});
});
});
My server route:
rest.post("/search", jsonParser, function(req, res){
/*some database action with redis */
res.json(dataJson);
});
});
My client route:
app.post('/search', jsonParser, function(req,res){
var test = JSON.stringify(req.body);
fs.readFile('./filterergebnis.ejs', {encoding: 'utf-8'}, function(err, filestring){
if(err){
throw err;
}
else{
var options = {
host: 'localhost',
port: 3000,
path: '/search',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': test.length
}
}
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
var userdata = JSON.parse(chunk);
console.log(userdata);
var html = ejs.render(filestring, userdata);
//here does the error appear...
res.setHeader('content-type', 'text/html');
res.writeHead(200);
res.write(html);
res.end();
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(test);
req.end();
}
});
});
This is what the error looks like:
http://www.pic-upload.de/view-28225954/stack.png.html
index.ejs is running on default
You're using conflicting res variable names. Check the variable names of the callbacks from app.post() and http.request().
If you change to response instead, it might work, if there is no other problems:
var req = http.request(options, function(response) {
response.on('data', function (chunk) {
...
In my express action get('items') I'm calling an external JSON-API and would like to render the API response in my local response.
Currently I get an error that my items variable is not defined inside of the http request. It seems this is a scope issue but I didn't find a solution.
What is the best way to accomplish this?
var http = require('http');
router.get('/items', function (req, res, next) {
var items;
var RemoteRequest = http.request({
method: 'GET',
path: 'myurl'
}, function (response) {
response.on('data', function (data) {
items = JSON.parse(data);
});
});
RemoteRequest .end();
res.render('new', {items: items} );
// or res.json({items: items});
});
It looks like you are not waiting for the return from your http request, you need to move the res.render('new', {items: items} ); into the callback:
var http = require('http');
router.get('/items', function (req, res, next) {
var items;
var RemoteRequest = http.request({
method: 'GET',
path: 'myurl'
}, function (response) {
response.on('data', function (data) {
items = JSON.parse(data);
res.render('new', {items: items} );
// or res.json({items: items});
});
});
RemoteRequest .end();
});