I'm trying to print the data which has been received at the server side but it always
shows a blank body output printing req={}
I've been trying for days and I can't find the answer, any help would be greatly appreciated!!!
the server side code:
const express= require('express');
const app=express();
const data_itself = require('./data.js');
app.use(express.static('public'));
app.use(express.urlencoded({extended:true}));
app.listen(3100,()=>{
console.log('sever listening at port 3100...')
});
app.set('view engine','ejs');
app.set('views','public');
app.get('/',(req,res)=>{
res.redirect('/home');
});
app.post('/',(req,res)=>{
var random_data='recived post request!'
res.send(random_data);
console.log('req=',req.body); //this outputs to req={}
});
The client side code:
<!DOCTYPE html>
<head>
<title>Sample Site</title>
</head>
<body>
<button onclick="send_info()">Submit data</button>
<div id="stat"></div>
</body>
<script>
data=['xyz'];
function send_info(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("stat").innerHTML =
this.responseText;
}
};
xhr.open("POST",'/', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
}
</script>
</html>
You need to have your express server use the JSON parser middleware. Add the following line to your server file.
app.use(express.json())
An explanation of the middleware is available at this link: http://expressjs.com/en/api.html
Related
Im trying to get an local txt file from calling a XMLHttpsRequest() method. But it keeps sending me a 404 error message in the console. Please help me out.
here is my html file
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Ajax1</title>
</head>
<body>
<button id="button" type="button" name="button">Get text files</button>
<script type="text/javascript">
document.getElementById("button").addEventListener('click', loadText)
function loadText(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
if(xhr.status === 200){
console.log(xhr.responseText)
}
}
xhr.send(null);
}
</script>
</body>
</html>
Local txt file is not inside any folder.
I dont know whether this is important or not but here is my app.js file
const express = require('express')
const app =express()
app.use(express.static("public"))
app.get('/', function(req, res){
res.sendFile(__dirname+'/ajax1.html')
})
app.listen(3000, function(){
console.log('server is runing')
})
here is my directory tree
`>Ajax-beginning
>node_modules
•Ajax.html
•app.js
•package-lock.jason
•package.jason
I am trying to make an upvote and downvote system in nodejs. The client side javascript should handle the upvote and downvote functionality and send the data to the server, which will store the decisions of the user.
My question is how do I send the data to the server and how can I send back if the upvote or downvote was successfully saved?
Client side:
window.onload = function() {
document
.getElementsByClassName("upvote")[0]
.addEventListener("click", function(event) {
// tell the server that the user upvoted
});
};
And on the server I would do something like this I guess
app.get("/", function(req, res) {
// save req data to a file
if (savedToFile) {
res.send("saved successfully");
}
else {
res.send("error");
}
});
I hope you are using pure javascript, then you can use Ajax to send get a request to the server like bellow inside the click event.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText; // here you get the response
}
// handle 500 error state here
};
xhttp.open("GET", "server_url/upvote", true);
xhttp.send();
After you save the data to database send the response as bellow
app.get("/upvote", function(req, res) {
// save req data to a file
if (savedToFile) {
res.status(200).send("saved successfully");
}
else { // if got any error
res.status(500).send("error");
}
});
I am making a put request from frontend for which I have been using XMLHttpRequest and FormData API request but server side I would not get any data like req.params, req.body and req.query all are empty
Front-end Code
var reportSub = () => {
var report = document.getElementById('report');
var formData = new FormData(report)
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.response)
}
}
var queryString = new URLSearchParams(formData);
xhr.open("PUT", '/threads/edit', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(queryString)
}
var reportsub = document.querySelector('#repsub');
reportsub.addEventListener("click",(e)=>{
e.preventDefault();
reportSub();
})
Server Side code
router.put('/threads/edit',(req,res)=>{
let board = req.body.board;
let id = req.body.id;
console.log(req.query,req.body)
Board.findById({_id: ObjectId(id)},(error,data)=>{
if(error)
res.send(error)
if(data!==null){
data.Reprot = true;
data.save((error,sd)=>{
if(error)
res.send(error)
res.send(sd);
})
}
else{
res.send({"Error":"Id does not exist "})
}
})
})
There is one solution would be where you add data in url which again hard coded each in every variable and data you had to pass.
So thats I want use FormData interface for sending data.
I think you are missing a library for parsing the FormData request. You could also send the data using JSON as it is text-only, this would simplify parsing. A minimal example could look like the following:
server.js
const express = require("express");
const multer = require("multer");
const upload = multer();
const app = express();
app.use(express.static('public'))
app.post('/data', upload.none(), function (req, res) {
console.log(req.body.favoriteNumber);
res.send('42 is the only real choice');
});
app.listen(3000, function () {
console.log('App listening on port 3000!');
});
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id="textForm">
<p>Your favorite number:</p>
<input type="text" value="42" name="favoriteNumber" />
</form>
<button id="send">Send</button>
<script>
const sendButton = document.getElementById("send");
const form = document.getElementById("textForm");
sendButton.addEventListener("click", () => {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.response);
}
}
const formData = new FormData(form);
xhr.open("POST", '/data', true);
xhr.send(formData);
})
</script>
</body>
</html>
You do not have to set the header manually. It is set automatically and does include boundary - a parameter you cannot know while writing the application. The header could look like the following:
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryuzeaYvzY77jzcFeA
I'm new to Node.js .
I'm trying to do a POST request to my Node.js server running locally on port 8080.
But it doesn't work.
FireFox block my POST request because it is cross-origin
Reason: CORS request not HTTP
Here is my code:
HTML
<html>
<head>
<title>Progetto Start</title>
<script src="..\Controller\Start.js"></script>
</head>
<body>
<input type="button" id="btPostJSON" value="invia JSON" onclick="SendJSON()"/>
</body>
</html>
Start.js:
function SendJSON() {
xhr = new XMLHttpRequest();
var url = "127.0.0.1:8080";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({"email":"tomb#raider.com","name":"LaraCroft"});
xhr.send(data);
}
Node js server:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write(req.url);
res.end();
console.log(req.url);
}).listen(8080);
I'm printing url to console and as a response only to see if it works
There is someone that has already solved mine problem ?
Just a quick note, CORS is required whenever the domain of the server/api does not match the domain of the calling client. If your port number on the client side does not match the port number on the server/api, the domains do not match and CORS is required
Shamelessly pulled from here: [https://bigcodenerd.org/enable-cors-node-js-without-express/][1]
Inside your createServer callback, put this:
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000, // 30 days
/** add other headers as per requirement */
};
if (req.method === 'OPTIONS') {
res.writeHead(204, headers);
res.end();
return;
}
if (['GET', 'POST'].indexOf(req.method) > -1) {
res.writeHead(200, headers);
res.end('Hello World'); //Replace this with your response logic
return;
}
The if (req.method == "OPTIONS") block is your 'pre-flight' request. This is basically just used to check cors permissions for a resource.
There's also other packages that will do something similar for you. Replace the "*" with your specific client-side hostname ("something.com") for better security. Using the wildcard (*) is a security risk, so before putting something in production, you'll want to change that to whatever domain or ip address you want to let access your api.
You are missing the protocol from your URL. Add http:// to it and it should work.
var url = "http://127.0.0.1:8080";
I don't have a specific question, but rather, I need something to be explained. I'm doing an assignment that requires that I use AJAX (WITHOUT JQuery) to display a list once the page loads. However, I'm confused about a part of the instructions.
"...presented with. Once the page loads, an Ajax call should call to a Node.js server to retrieve the top 10 list. Then the list must be presented to the user as numbered list. The items..."
Does this mean I need to create another Node.js server in addition the one I've already created or can this all be done within one server? I'm very confused about this part.
This is my Node.js server.
'use strict';
const express = require('express'),
request = require('request'),
app = express();
app.set('view engine', 'pug');
app.set('views', './views');
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.use(express.static('public'));
app.get('/', function (req, res) {
res.render('index');
});
app.listen(3000, function () {
console.log('Listening on http://localhost:3000');
});
This is my PUG template.
doctype
html
head
meta(charset="UTF-8")
meta(name="viewport", content="width=device-width, initial-scale=1")
block title
title This is the title!
link(rel='stylesheet', href='/css/style.css', type='text/css')
body
h1 This is a header!
div#banner
p#demo This is a description!
script(src='/js/mrvl_ajax.js')
This is my AJAX call function.
'use strict';
window.addEventListener("load", function(event) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById("demo").innerHTML = this.responseText;
};
xhttp.open("GET", "**Server Location?**", true);
xhttp.send();
});
You can create another endpoint on your Node.js server.
app.get('/data', function (req, res) {
res.json({"list": ["item1", "item2"]});
});
then call that endpoint from the client with ajax
xhttp.open("GET", "/data", true);
the data returned will be the JSON data {"list":["item1", "item2"]}, which you can then use javascript to order it how you need to.
also, inside your onreadystatechange function you will want this if statement to make sure the call completed successfully before you grab the responseText from the response
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4 && xhttp.status === 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
}