here is the url in browser
http://localhost:8888/update/1
this is the code for the route
router.addRoute("/update/:id", (req, res) => {
conn.query(
"select * from mahasiswa where ? ",
{ no_induk: req.params.id },
function (err, rows, field) {
if (rows.length) {
if (req.method.toUpperCase() == "POST") {
} else {
let html = view.compileFile("./tamplate/form_update.html")();
res.writeHead(200, { "Contact-Type": "text/html" });
res.end(html);
}
} else {
let html = view.compileFile("./tamplate/form_update.html")();
res.writeHead(200, { "Contact-Type": "text/html" });
res.end(html);
}
}
);
});
please help me i have no idea
I think it's better to use router.post
For example:
router.post("/update/:id", (req, res) => {
conn.query(
"select * from mahasiswa where ? ",
{ no_induk: req.params.id },
function (err, rows, field) {
if (rows.length) {
let html = view.compileFile("./tamplate/form_update.html")();
res.writeHead(200, { "Contact-Type": "text/html" });
res.end(html);
}
}
});
Related
const server = http.createServer((req, res) => {
const pathName = req.url;
if(pathName === '/' || pathName === '/overview') {
res.end('This is the overview');
} else if (pathName === '/product') {
res.end('This is the product');
} else if (pathName === '/api') {
fs.readFileSync(`${__dirname}/starter/dev-data/data.json`, 'utf-8', (err, data) => {
const productData = JSON.parse(data);
res.writeHead(200, { 'Content-type': 'application/json'})
res.end(data);
});
} else {
res.writeHead(404, {
'Content-type': 'text/html',
'my-own-header': 'hello-world'
});
res.end('<h1>Page not found</h1>');
}
});
server.listen(8000, '127.0.0.1', () => {
console.log('Listening to requests on port 8000');
});
I'm trying to get some data to render onto the page though it's not working. I've included a picture of what my environment looks like.
I think the forward slashes in fs.readFileSync(`${__dirname}/starter/dev-data/data.json, 'utf-8', (err, data) => should be back slashes.
I got a fetched error type when trying to send data from a react app .
note that I m using cores.
and it s working fine on localhost with client side and not when hosting it online.
Note : I get result from json when using postman like this :
{
"success":"true",
"ID":"token"
}
this is the back-end code source in expressjs :
router.post("/sickers/user/login/", cors(), (req, res) => {
var values = req.body;
var pass = values.password;
var email = values.email;
if (pass !== null || pass !== "") {
try {
con.query("SELECT Password ,ID FROM `sickers` WHERE Email='" + email + "'", function(err, rows, field) {
if (err) {
console.log(err);
res.send("an error detected try later");
} else {
try {
if (pass == rows[0].Password) {
//create the signed function
jwt.sign(rows[0].ID, "secretkey", (err, token) => {
res.json({ success: "true", ID: token })
})
//session.session( )
} else {
res.json({ success: "false" });
}
} catch {
res.json({ success: "false" });
}
}
});
} catch (e) {
res.json({ success: "false" });
}
}
});
and client method is :
//submit values
const submithandler=async (e)=> {
e.preventDefault();
try{
console.log('start')
await fetch('url/api/sickers/user/login/',{
method:'post',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({
password:password,
email:email
})
})
.then(response =>
{
console.log("response");
response.json().then(data =>
{
console.log(data);
if(data.success=="true")
{
sessionStorage.setItem('ID',data.ID);
window.location.reload();
seterr("");
}
else
{
seterr("try again");
}
});
});
}
catch(e)
{
console.log(e)
}
}
do I miss something here?
thanks in advance.
I solved this before by adding cores to .htaccess on server , or hosting the full project with it's back and front ends into the same server.
How to fix this error message?
[xhr.js?b50d:178 POST http://localhost:3000/editor/add net::ERR_CONNECTION_RESET][1]
It works and append data, but I get this error message...
My API looks like this:
app.js
app.post('/editor/add', function (req, res) {
let articleData;
let textData;
let article = {
title: req.body.title,
content: req.body.content
}
fs.readFile(urlPath, 'utf8', (err, data) => {
if (err) {
console.log('readfile => ' + err);
} else {
articleData = JSON.parse(data);
articleData[article.title] = article.content;
textData = JSON.stringify(articleData, null, 2);
fs.writeFile(urlPath, textData, 'utf8', (err) => {
if (err) {
console.log('write file => ' + err);
} else {
console.log('Finished writing');
}
});
}
});
});
And my Axios POST method looks like this.
editor.vue
submitEditor: function() {
var self = this;
self.$axios({
headers: {
"Content-Type": "application/json"
},
method: "post",
url: "http://localhost:3000/editor/add",
data: {
title: "test5",
content: self.html
}
})
.then(res => {
console.log(res);
})
.catch(error => {
if (!error.response) {
// network error
this.errorStatus = "Error: Network Error";
} else {
this.errorStatus = error.response.data.message;
}
});
}
I use Vue/cli, I separate my client code and my server code. They are on a separate folder. I put Vue/cli in my client folder, and express.js in my server folder.
Thank you in advance!
Try sending a response from your route:
fs.writeFile(urlPath, textData, 'utf8', (err) => {
if (err) {
console.log('write file => ' + err);
} else {
console.log('Finished writing');
res.json({ msg: 'success' }); // send the client something
}
});
I am trying learn nodejs and stumble upon this error
TypeError: callback is not a function
when I am trying to call the server using this command.
curl http://localhost:8090/albums.json
and here is the code for my server.js
var http = require('http'),
fs = require('fs');
function load_album(album_name, callback) {
fs.readdir("albums/", +album_name, (err, files) => {
if (err) {
if (err.code == "ENOENT") {
callback(make_error("no_such_album", "That album doesn't exist"));
} else {
callback(make_error("can't load album", "The server is broken"));
}
} else {
//callback(null, files);
var only_files = [];
var path = 'albums/${album_name}/';
var iterator = (index) => {
if (index == files.length) {
var obj = {
short_name: album_name,
photos: only_files
};
callback(null, obj);
return;
}
fs.stat(path + files[index], (err, stats) => {
if (!err && stats.isFile()) {
only_files.push(files[index]);
}
iterator(index + 1);
});
};
iterator(0);
}
});
}
function handle_incoming_request(req, res) {
console.log("incoming request: " + req.method + " " + req.url);
if (req.url == '/albums.json') {
load_album((err, albums) => {
if (err) {
res.writeHead(500, {
"Content-Type": "application/json "
});
res.end(JSON.stringify({
code: "cant_load_albums",
message: err.message
}));
} else {
var output = {
error: null,
data: {
albums: albums
}
};
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify(output) + "\n");
}
});
} else if (req.url.substr(0, 7) == '/albums' && req.url.substr(req.url.length - 5) == '.json') {
//user is requesting contents of album
load_album(req.url.substr(7, req.url.length - 12), (err, photos) => {
if (err) {
res.writeHead(500, {
"Content-type": "application/json"
});
res.end(JSON.stringify(err));
} else {
var output = {
error: null,
data: {
photos: photos
}
};
res.writeHead(200, {
"Content-Type": application / json
});
res.end(JSON.stringify(output) + "\n");
}
});
} else {
res.writeHead(404, {
"Content-type": "application/json"
});
res.end(JSON.stringify({
code: "no_such_page",
message: "No such page"
}));
}
}
var s = http.createServer(handle_incoming_request);
s.listen(8090);
can you tell me what's wrong with my code that I got an error telling me callback isn't a function?
thanks though
for more formatted code then you can go here https://jsfiddle.net/02dbx6m9/
var http = require('http'),
fs = require('fs');
function load_album(album_name, callback) {
fs.readdir("albums/", +album_name, (err, files) => {
if (err) {
if (err.code == "ENOENT") {
callback(make_error("no_such_album", "That album doesn't exist"));
} else {
callback(make_error("can't load album", "The server is broken"));
}
} else {
//callback(null, files);
var only_files = [];
var path = 'albums/${album_name}/';
var iterator = (index) => {
if (index == files.length) {
var obj = {
short_name: album_name,
photos: only_files
};
callback(null, obj);
return;
}
fs.stat(path + files[index], (err, stats) => {
if (!err && stats.isFile()) {
only_files.push(files[index]);
}
iterator(index + 1);
});
};
iterator(0);
}
});
}
function handle_incoming_request(req, res) {
console.log("incoming request: " + req.method + " " + req.url);
if (req.url == '/albums.json') {
load_album("ALBUM NAME", (err, albums) => {
if (err) {
res.writeHead(500, {
"Content-Type": "application/json "
});
res.end(JSON.stringify({
code: "cant_load_albums",
message: err.message
}));
} else {
var output = {
error: null,
data: {
albums: albums
}
};
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify(output) + "\n");
}
});
} else if (req.url.substr(0, 7) == '/albums' && req.url.substr(req.url.length - 5) == '.json') {
//user is requesting contents of album
load_album("Album Name", req.url.substr(7, req.url.length - 12), (err, photos) => {
if (err) {
res.writeHead(500, {
"Content-type": "application/json"
});
res.end(JSON.stringify(err));
} else {
var output = {
error: null,
data: {
photos: photos
}
};
res.writeHead(200, {
"Content-Type": application / json
});
res.end(JSON.stringify(output) + "\n");
}
});
} else {
res.writeHead(404, {
"Content-type": "application/json"
});
res.end(JSON.stringify({
code: "no_such_page",
message: "No such page"
}));
}
}
var s = http.createServer(handle_incoming_request);
s.listen(8090);
You forgot to pass album name parameter in load_album method. That's why album_name parameter is assigned the actual callback, while callback parameter remains undefined.
Here is the root cause of your issue:
load_album((err, albums) => {
// ...
});
The signature for the function requires two parameters, yet you're only passing the first one:
function load_album(album_name, callback) {}
Therein, once called, callback will be undefined, yet you're trying to treat it as a callable. Here's a more succint example of how to reproduce the error:
function foo(bar, baz) {
baz()
}
foo(() => {})
module.exports.login = function (request, response, next) {
if (request.body.user && request.body.password) {
response.end('submitted');
} else {
common.render('login', function (error, file) {
if (error) {
next(error);
} else {
response.writeHead(200, 'OK', { 'Content-Type': 'text/html' });
var stream = fs.createReadStream(file);
stream.pipe(response);
}
});
}
};
I am using connect with body-parser. When I first time open this app I see login form - nice, but when I submit a form I see in a console 405 Method not allowed error. I was trying to add some headers but it didn't work. Anyone can help?
I finally solved it. The problem was serve-static and serve-index. It was written some extra headers like allowed methods!
I believe the syntax should be:
module.exports = function(request, response, next) {
if (request.body.user && request.body.password) {
response.end('submitted');
} else {
common.render('login', function (error, file) {
if (error) {
next(error);
} else {
response.writeHead(200, 'OK', { 'Content-Type': 'text/html' });
var stream = fs.createReadStream(file);
stream.pipe(response);
}
});
}
};
or
function login(request, response, next) {
if (request.body.user && request.body.password) {
response.end('submitted');
} else {
common.render('login', function (error, file) {
if (error) {
next(error);
} else {
response.writeHead(200, 'OK', { 'Content-Type': 'text/html' });
var stream = fs.createReadStream(file);
stream.pipe(response);
}
});
}
};
module.exports = login;