It should redirect back to the "/" root url, but somehow it's not working properly.
it gives the 302 confirmation, but it wont get there
const fs = require("fs");
function requestHandler(req, res) {
const url = req.url;
const method = req.method;
if (url === "/") {
res.write("<html>");
res.write("<head><title> Minha primeira página! </title></head>");
res.write(
"<body><form action='/message' method='POST'><input type='text' name ='message'><button type='submit'>Enviar</button></form></body>"
);
res.write("</html>");
return res.end();
}
//console.log(req.url, req.method, req.headers);
if (url === "/message" && method === "POST") {
const body = [];
req.on("data", (chunk) => {
console.log(chunk);
body.push(chunk);
});
req.on("end", () => {
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split("=")[1];
fs.writeFile("message.txt", message, (err) => {});
});
res.statusCode = 302;
res.setHeader = ("Location", "/");
return res.end();
}
}
Redirect to "/" after solving /message
You can use redirect to go to the home page like
res.redirect('/');
Related
So I'm building a dashboard, where you can log in with Discord then it shows your profile picture and username. I use node js as the server side. The problem is that I have got the code, everything works normal, but I want to access the Discord username on every hosted page. Currently, I try to save the data into the localStorage but I cannot see anything to be saved inside it. I will share my server-side and client side code here. Thanks for any help!
My index.js (server side):
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const fetch = require('node-fetch');
const FormData = require('form-data');
var path = require('path');
const axios = require("axios")
const process = require("process")
app.use(bodyParser.text());
app.use(express.static(path.join(__dirname, '/')));
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.get('/', function (req,res){
res.sendFile(__dirname + "/" + "home.html")
})
/*app.get('/dashboard', function (req, res){
res.sendFile(__dirname + "/dashboard/" + "home.html")
})*/
app.post('/', function (req, res) {
const data = new FormData();
console.log(req.body)
data.append('client_id', process.env.CLIENT_ID);
data.append('client_secret', process.env.CLIENT_SECRET);
data.append('grant_type', 'authorization_code');
data.append('redirect_uri', "https://sovietweb.petertill1.repl.co/home.html");
data.append('scope', 'identify');
data.append('code', req.body);
fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: data,
})
.then(response => response.json())
.then(data=>{
console.log(data)
const config = {
headers:{
"authorization":`Bearer ${data.access_token}`
}
}
axios
.get("https://discordapp.com/api/users/#me",config)
.then(response=>{
console.log(response.data.username)
console.log(response.data.id)
//username,id,avatar,discriminator
//res.send(response.data.username)
//res.send(response.data.avatar)
res.send(response.data.username + "," + response.data.id + "," + response.data.avatar + "," + response.data.discriminator)
})
.catch(error=>{
console.log(error)
})
})
})
app.listen(8081)
My home.html js snippet (the dashboard client side getting the response from the server side. I need to access the username on every hosted page):
window.onload = () => {
const code = location.href.substring(location.href.indexOf("code")+5, location.href.length)
if (location.href.indexOf("code") > -1) {
const req = new XMLHttpRequest()
req.open("POST", "https://sovietweb.petertill1.repl.co")
req.send(code)
req.onload = () => {
str = req.responseText;
const data = str.split(',');
//belépve
if (req.status === 500) { // Error
alert("Error 500");
} else if (req.status === 200) { // Successful
document.getElementsByClassName('pfp').src = `https://cdn.discordapp.com/avatars/${data[1]}/${data[2]}`;
document.getElementsByClassName('uname').innerHTML = `${data[0]}#${data[3]}`;
} else if (req.status === 1015) {
alert("Ratelimit elérve! Várj egy keveset")
} else { // Other
alert("Más hiba!");
}
//alert(data[0]);
//username,id,avatar,discriminator
// document.getElementById("pfp").src = `https://cdn.discordapp.com/avatars/${data[1]}/${data[2]}`
// document.getElementById("display_result").innerText = `your username is ${data[0]}#${data[3]}`
}
}
}
Everything worked for me until I added csrf. I use in public/js/editor.js fetch to send the image file to the server:
fetch('/upload', {
method: 'post',
body: formdata
}).then(res => res.json())
.then(data => {
if (uploadType == 'image')
{
addImage(data, file.name);
}
else if (uploadType == 'banner')
{
bannerPath = `${location.origin}/${data}`;
banner.style.backgroundImage = `url("${bannerPath}")`
}
else
{
console.error('Данный тип файла не поддерживается');
}
})
In the server.js I accept the file:
app.post('/upload', (req, res) => {
console.log(req.files);
let file = req.files.image;
let date = new Date();
console.log('test post');
// image name
let imagename = date.getDate() + date.getTime() + file.name;
// image upload path
let path = 'public/uploads/' + imagename;
// create upload
file.mv(path, (err, result) => {
if (err) {
throw err;
} else {
// our image upload path
res.json(`uploads/${imagename}`)
}
})
})
After adding csrf files began to look like this:
Become:
editor.js FULL
const csrfToken = getCookie('XSRF-TOKEN');
console.log(csrfToken);
const headers = new Headers({
'Content-Type': 'x-www-form-urlencoded',
'X-CSRF-Token': csrfToken
});
fetch('/upload', {
method: 'post',
headers: headers,
credentials: 'include',
body: formdata
}).then(res => res.json())
.then(data => {
if (uploadType == 'image')
{
addImage(data, file.name);
}
else if (uploadType == 'banner')
{
bannerPath = `${location.origin}/${data}`;
banner.style.backgroundImage = `url("${bannerPath}")`
}
else
{
console.error('Данный тип файла не поддерживается');
}
})
function getCookie(name) {
if (!document.cookie) {
return null;
}
const xsrfCookies = document.cookie.split(';')
.map(c => c.trim())
.filter(c => c.startsWith(name + '='));
if (xsrfCookies.length === 0) {
return null;
}
return decodeURIComponent(xsrfCookies[0].split('=')[1]);
}
and server.js FULL
const cookieParser = require("cookie-parser");
const csrf = require("csurf");
const csrfMiddleware = csrf({ cookie: true });
app.use(cookieParser());
app.use(csrfMiddleware);
app.all("*", (req, res, next) => {
var token = req.csrfToken();
res.cookie("XSRF-TOKEN", token);
res.locals.csrfToken = token;
next();
});
app.use(function (req, res, next) {
var token = req.csrfToken();
res.cookie('XSRF-TOKEN', token);
res.locals.csrfToken = token;
next();
});
//upload link
app.post('/upload', (req, res) => {
console.log(req.files);
let file = req.files.image;
let date = new Date();
console.log('test post');
// image name
let imagename = date.getDate() + date.getTime() + file.name;
// image upload path
let path = 'public/uploads/' + imagename;
// create upload
file.mv(path, (err, result) => {
if (err) {
throw err;
} else {
// our image upload path
res.json(`uploads/${imagename}`)
}
})
})
Problem
But now after uploading the image to editor.js , an error occurs in server.js:
TypeError: Cannot read properties of undefined (reading 'image')
The variable req.files has become undefined
What is the problem?
'Content-Type': 'x-www-form-urlencoded',
You're overriding the Content-Type header the browser was sending with the request.
Since the new value is wrong, the server doesn't know how to parse the body.
Don't do that.
I created a server without express and I'm trying to server a simple static webpage on localhost
here is my code :
const fs = require('fs')
const url = require('url');
const hostname = 'localhost'
const port = 3000;
const path = require ('path');
const http = require ('http')
const server = http.createServer((req, res) => {
if (req.url.match (/.css$/)) {
let cssPath = path.join (__dirname, req.url)
let cssReadStream = fs.createReadStream (cssPath, 'UTF-8')
res.statusCode = 200;
res.setHeader ("Content-Type", "text/css");
cssReadStream.pipe (res)
}
if (req.url === "/") {
fs.readFile("./index.html", 'UTF-8', (err, data) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
res.end(data);
})
}
if (req.url.match (/.jpg$/)) {
let jpgPath = path.join (req.url)
console.log (jpgPath)
let jpgReadStream = fs.createReadStream (jpgPath, 'UTF-8')
res.statusCode = 200;
res.setHeader ('Content-Type', 'image/jpg')
jpgReadStream.pipe (res)
}
})
server.listen (port, hostname, () => {
console.log ('server start')
})
first of all, it can display the HTML and CSS, however, localhost just keeps on loading after HTML and CSS displayed. Second of All, the image cannot be display (a instagram icon name icon.jpg).
the end result should look something like this:
I guess it has something to do with the favicon thing, but how do i fix it?
you need to use response.send() function which will be used to send the response back
const server = http.createServer((req, res) => {
if (req.url.match (/.css$/)) {
let cssPath = path.join (__dirname, req.url)
let cssReadStream = fs.createReadStream (cssPath, 'UTF-8')
res.statusCode = 200;
res.setHeader ("Content-Type", "text/css");
cssReadStream.pipe (res)
res.send("your data")
}
if (req.url === "/") {
fs.readFile("./index.html", 'UTF-8', (err, data) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
res.end(data);
res.send("your data")
})
}
if (req.url.match (/.jpg$/)) {
let jpgPath = path.join (req.url)
console.log (jpgPath)
let jpgReadStream = fs.createReadStream (jpgPath, 'UTF-8')
res.statusCode = 200;
res.setHeader ('Content-Type', 'image/jpg')
jpgReadStream.pipe (res)
res.send("your data")
}
})
The function activated by the listener on http.incomingMessage is not working properly, it is supposed to define the constant chunk white the submited input but for some reason it remain UNDEFINED.
I dont get any error message but the page wont stop loading after accessing the page.
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
if (url === '/') {
res.write('<html>');
res.write('<head><title>Enter Message</title></head>');
res.write('<body>');
res.write('<form action="/message" method="POST">');
res.write('<input type="text">');
res.write('<input type="submit">');
res.write('</form>');
res.write('</body>');
res.write('</html>');
return res.end();
}
if (url === '/message') {
const body = [];
req.on('data', chunk => {
body.push(chunk);
});
return req.on('end', () => {
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split('=')[1];
console.log(parsedBody);
fs.writeFileSync('message.txt', message, err => {
res.statusCode = 302;
res.setHeader('Location', '/');
return res.end();
});
});
}
res.setHeader('Content-Type', 'text/html')
res.write('<html>');
res.write('<head><title>Enter Message</title></head>');
res.write('<body>');
res.write('<p>My page</p>');
res.write('</body>');
res.write('</html>');
res.end();
});
server.listen(8080);
You are not calling the function properly, change your res.end; to res.end();.
In order to finish sending a request you have to invoke the res.end() function
I'm new in node.js and I'm implementing a Static file server.
what i'm trying to do is just get the file name from the url and display it. running the code id get this error:
_http_outgoing.js:489
throw new Error('Can\'t set headers after they are sent.');
Error: Can't set headers after they are sent.
this is my code
#!/usr/bin/env node
/*
* Basic node.js HTTP server
*/
const http = require('http');
const url = require('url');
const fs = require('fs');
const routes = Object.create(null);
function file(rew, res, serched) {
let fileSerched = serched[serched.length - 1]
fileSerched = __dirname + "/NodeStaticFiles/" + fileSerched;
fs.readFile(fileSerched, function(err, data) {
if (err) {
res.statusCode = 500;
res.end(`Error getting the file: ${err}.`);
} else {
res.setHeader('Content-type', 'text/plain');
res.writeHead(200)
res.end(data);
}
})
}
routes['file'] = file;
function onRequest(req, res) {
const pathname = url.parse(req.url).pathname
const uri = pathname.split('/', 3)[1]
let splittedPathname = pathname.split('/')
splittedPathname.shift()
splittedPathname.shift()
if (typeof routes[uri] === 'function') {
routes[uri](req, res, splittedPathname);
} else {
res.statusCode = 404;
res.end(`File not found!`);
}
res.end()
}
http.createServer(onRequest).listen(3000);
console.log('Server started at localhost:3000')
You need to make sure your code won't call something like res.end() more than once. For example:
function onRequest(req, res) {
const pathname = url.parse(req.url).pathname
const uri = pathname.split('/', 3)[1]
let splittedPathname = pathname.split('/')
splittedPathname.shift()
splittedPathname.shift()
if (typeof routes[uri] === 'function') {
routes[uri](req, res, splittedPathname);
} else {
// THIS WILL CALL res.end() and continue on
res.statusCode = 404;
res.end(`File not found!`);
}
// THIS WILL CALL res.end() AGAIN!!
res.end()
}
try adding a return after you call res.end() in an if/else