trouble in sending data through ajax to express server - html

I'm new to backend and I was having some trouble in sending data through vanilla ajax to my express server.
please tell me where am I going wrong
my ajax request:
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.withCredentials = true;
xhttp.send("name=abhishek");
my express server:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors({
credentials:true,
origin:'http://127.0.0.1:5500'
}));
var PORT = process.env.PORT || 8080;
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/', function(req, res){
console.log(req.query);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
I'm receiving an empty object as the output in my console

There are few things to change.
The client is a POST request but in server side, it is a GET app.get(). Therefore, nothing displayed after request.
Also, Content-type needs to be set to inform server how it is going to parse the message. e.g. JSON/form-data
I assume you want to use POST, below is the change:
Backend:
Change method from app.get to app.post
Get the data from body instead of query
...
app.post("/", function (req, res) {
console.log(req.body); // data is in body instead of query
res.send("hi"); // send back response to frontend
});
...
Frontend:
Set content-type
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(xhttp.responseText); // should receive hi
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.withCredentials = true;
xhttp.send("name=abhishek");

Related

To forward a JSON file to other Address with Express js

Just starting to learn express. Would wish to forward a json file to another location for processing/ingestion that i recieved from a request from webhook using POST url endpoint.
I am planning to pass this json file to a cpp program
I have the following code
var request = require('request'),,
express = require('express'),
path = require('path');
http = require('http');
const port = 5000;
var app = express();
// for json parser
app.use(express.json());
app.post('/gethub', function(req, res) {
console.log("Got response: " + res.statusCode);
console.log("Got header: " + res.getHeaderNames());
console.log("Got status Message: " + res.statusMessage );
var data = req.body;
var name = data.pusher.name;
var node_id = data.sender.node_id;
res.status(200).send(res.json( { name : name,
Nodeid : node_id });
});
var server = app.listen(app.get('port'), function() {
var host = server.address().address
var portid = server.address().port
console.log('App listening at http://%s:%s', host, portid)
console.log("App listening on port " + app.get('port'));
});
THanks for your help
Think of Express as a framework that behaves as a web server. What you really are doing is writing an API listening in the port 5000 in your case. The function seems ok so it will be accesible while making a HTTP request using the POST method.
Express docs about routing

Can feathers co exist with routs managed out side of feathers

We have a large app which uses express for rest and primus for socket routes. It would be very hard to convert all to feathers at once. I am thinking of phased approach where I could take some routes and convert them to services and of cause any new routes will follow the service pattern. I will slowly migrate the rest of the app.
The client is using primus and angularjs $http for now to communicate with nodejs.
our current set up looks like
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
const csrf = require('csurf');
var Primus = require('primus');
var SocketService = require('./../services/socket-service'); ////this handles existing socket routes from primus client using spark.write
var routesUtils = require('../utilities/routes-utility');
var _ = require('lodash');
module.exports = function(isClusteredDeploy) {
var app = express();
var server = http.createServer(app);
var primus = new Primus(server, {transformer: 'uws'});
var socketService = SocketService(primus);
var commonSocketRoute, commonRoute;
//primus.library();
//primus.save(__dirname + '/primus-client.js');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json({
strict: false,
limit: '1mb'
}));
app.use(cookieParser());
app.use(csrf({ cookie: true }));
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') {
return next(err);
}
res.status(403);
res.send();
});
app.use(function(req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
next();
});
server.listen(config.get(constants.CONFIG_App_Port), function() {
log.info('App server ==> %s is listening on port %d', config.get('rest_host_config.' + config.get('app_key') + '.host'),
config.get(constants.CONFIG_App_Port));
});
//dynamically loading rest routes and socket routes from the file system
var files = routesUtils.readRoutes(true);
files.forEach(function(file) {
if (_.includes(file, 'socket')) {
commonSocketRoute = require('./../../' + file);
commonSocketRoute(socketService);
} else {
commonRoute = require('./../../' + file);
commonRoute(app);
}
});
};
I'd like to add feathers in this and then slowly start converting. Is this possible?
Yes, with the standard #feathersjs/express framework integration your Feathers application will also be a fully Express compatible application which additionally allows to register services.
In your case you would replace var app = express(); with:
const feathers = require('#feathersjs/feathers');
const express = require('#feathersjs/express');
// Create an app that is a Feathers AND Express application
const app = express(feathers());
// Set up REST services (optional)
app.configure(express.rest());
And everything should continue to work as normal. The next step would be to replace the custom Primus code with the #feathersjs/primus framework adapter:
const feathers = require('#feathersjs/feathers');
const express = require('#feathersjs/express');
const primus = require('#feathersjs/primus');
// Create an app that is a Feathers AND Express application
const app = express(feathers());
// Set up Primus with SockJS
app.configure(primus({ transformer: 'ws' }));
Now you can also replace the http.createServer setup with a more simple
const server = app.listen(config.get(constants.CONFIG_App_Port))
Since Feathers will handle all the Express and Primus initialization. The Primus instance will be available as app.primus.

sending json data response

I am trying to send a JSON response via HTTP but unfortunately, I don't see any response, I cant understand why really.
It looks like the response variable is not being sent.I am not sure the problem is that it is a JSON object or the way I am sending it.I am new to web development.
The requirement is to help user see the time and the name of the file which was usccessfully sent through.
var express = require('express');
var fs = require('fs');
var cors = require('cors');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = express();
var upload = multer({ dest: 'uploads/' });
var Client = require('ssh2').Client;
const request = require('request');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
app.get('/', function(req, res){
console.log('GET /');
//var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
var html = fs.readFileSync('index.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
app.post('/', upload.single('file'), function(req, res){
var response;
var time;
console.log('POST /');
console.dir(req.body);
// console.log(req.body.filename);
fs.writeFile('./uploads/' + req.body.filename, req.body.file,
function(err) { console.log(err)});
var conn = new Client();
conn.on('ready', function() {
console.log('Client :: ready');
conn.sftp(function(err, sftp) {
if (err) throw err;
// sftp.fastPut('./uploads/' + req.body.filename, '/data/' +
req.body.filename, function (err) {
// if (err) {
// console.log(err);
// throw err;
// }
// });
sftp.readdir('data', function(err, name) {
if (err) throw err;
console.dir(name);
var infoList = JSON.parse(JSON.stringify(name));
for(var index in infoList) {
var value = infoList[index];
time = value.attrs.mtime;
console.log(value.filename);
console.log(time);
response = JSON.stringify(value.filename);
}
conn.end();
});
});
}).connect({
host: 'ftp.amadeus.net',
port: 15022,
username: 'wtl001',
password: 'Wyamp309$'
});
res.writeHead(200, {'Content-Type': 'application/json', "Access-Control-
Allow-Origin": "*"});
res.json(response);
res.end("EOF");
});
port = 12811;
app.listen(port);
console.log('Listening at http://localhost:' + port);

Gets Error when adding MySQL information in server.js when creating RESTful API with Express

I was following instructions to build a RESTful API with Express and MySQL(*1)
But when I change
app.listen(port); //excutable, GET returns welcome message
into
orm.initialize(WConfig.config,function(err,models){
...
in the part 2 of(*1), which is adding MySQL information into server.js,
I gets the following on Node.JS command prompt:
TypeError: Cannot read property 'bear' of undefined
Because this is the first attempt in building RESTful API, I'm not sure what to do to fix it. Help please! Any idea is appreciated.
full code of server.js:
// server.js
var util = require('util');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var Waterline = require('waterline');
var Bear = require('./app/models/bear');
var WConfig = require('./app/config/waterline');
var orm = new Waterline();
orm.loadCollection(Bear);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'hello! welcome to our api!' });
});
app.use('/api', router);
// express deprecated res.json(obj,status): use res.status(status).json(obj) instead
router.route('/bears')
.post(function(req,res) {
app.models.bear.create(req.body,function(err,model) {
if(err) return res.status(500).json({ err,err });
res.json(model); //res.json(model) , guess: res.status(200).json(model);
console.log(util.inspect(model));
});
});
//gets error if I change it to following
//
orm.initialize(WConfig.config,function(err,models){
if(err) throw err;
app.models = models.collections;
//app.set('models',models.collections);
app.connections = models.connections;
app.listen(port);
console.log('Magic happens on port ' + port);
});
reference:
1.Create Restful API with Express and waterline (in Chinese)
https://segmentfault.com/a/1190000004996659#articleHeader2
2.Build a RESTful API Using Node and Express 4
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

How to connect static HTML and CSS files to Node.js application?

I try to show a (static) HTML webpage via Heroku. I have followed this tutorial: https://www.youtube.com/watch?v=gAwH1kSODVQ but after many attempts it is still not working.
I'm rather new to coding, so if you can give concrete examples that would be great!
The following files have been pushed to heroku:
server.js
package.json
Procfile.js
(folder) public with index.html, main.css
//Server.js file:
var express = require('express'); //require express module in server.js file
var app = express();
var mongojs = require('mongojs');
var db = mongojs('birthdaylist', ['birthdaylist']);
var bodyParser = require('body-parser');
var http = require('http');
var port = Number(process.env.PORT || 3000);
app.use(express.static(__dirname + '/public')); //connect to html file
app.use(bodyParser.json());
app.get('/birthdaylist', function(req, res) {
console.log("The server has received a GET request.")
db.birthdaylist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/birthdaylist', function(req, res){
console.log(req.body);
db.birthdaylist.insert(req.body, function (err, doc){
res.json(doc);
});
});
app.delete('/birthdaylist/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.birthdaylist.remove({_id: mongojs.ObjectId(id)}, function(err, doc){
res.json(doc);
});
});
app.listen(port, function () {
});
you should use:
app.listen(%PORT_NUMBER%, function () {
// some code here
});
Instead of:
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end('<h6>Hello worldsfasfd!</h6>');
});