Navigate to a page after a GET request in express? - ajax

I'm fairly new to express and was wondering how to navigate to a page as a result of a GET request? I'm building my page from a template, and the following works if I manually input the '/id' url:
const express = require('express');
const template = require('./template.js');
const app = express();
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send(template({
body: "Home",
title: "Home Title"
}))
});
app.get('/id', (req, res) => {
console.log("received get request for id");
res.send(template({
body: "id",
title: "ID"
}));
});
const server = app.listen(port);
console.log("listening...");
But if I send a GET request from the client, it gets received and nothing happens. Any tips or help would be appreciated! Thank you!

Related

I am getting get polling-xhr.js:157 404 error on my website

I am using server.js code
const { startCon } = require('./server/WaConnection')
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
const router = express.Router();
const { Server } = require('socket.io');
const io = new Server(server);
app.use(express.json());
app.use(express.urlencoded({ extended: true, limit: '50mb', parameterLimit: 1000000 }))
app.use(router);
require('./server/Routes')(router)
io.on('connection', (socket) => {
socket.on('StartConnection', async (device) => {
startCon(device, socket)
return;
})
socket.on('LogoutDevice', (device) => {
startCon(device, socket, true)
return
})
})
server.listen(process.env.PORT_NODE, () => {
console.log(`Server running on port ${process.env.PORT_NODE}`);
})
I am getting the error again and again that
enter image description here
I will be very thank full if you reslove my issue

Req.body from post returns as undefined no matter how I send it

This question has been asked but none of the answers help me figure this out. I'm passing a variable through ajax like so:
var myData = "Hi Og";
$.ajax({
type: 'POST',
data: myData,
url: 'https://example.com:8443',
success: function (data) {
alert(data);
}
});
In my express server I have this in my server.js
var fs = require('fs');
var http = require('http');
var https = require('https');
var bodyParser = require('body-parser')
var privateKey = fs.readFileSync('certificates/key.pem', 'utf8');
var certificate = fs.readFileSync('certificates/cert.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();
app.use( bodyParser.json() ); // to support JSON-encoded bodies
// your express configuration here
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
// For http
httpServer.listen(8080);
// For https
httpsServer.listen(8443);
app.post('/', function (req, res) {
console.log(req.body.myData);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Content-type', 'text/html');
return res.end('<h1>Hello, Secure World!</h1>');
});
With the above code I get a response back at the originating sender with the alert "Hello, Secure World!". However in the console I get "undefined".
I changed the content-type to application/json but that gave me a 500 error. I changed req.body.data and same thing undefined. req.body gives me this = {}
Per #robertklep direction I needed to property parse the body of the data with app.use( bodyParser.urlencoded() );
I incorrectly had this as json which was causing it to be undefined.

koa2 post always show Method Not Allowed?

//server.js
const Koa = require('koa')
const app = new Koa();
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
const Router = require('koa-router');
const fs = require('fs');
const router = new Router();
const UserController = require('./server/controller/user.js');
const checkToken = require('./server/token/checkToken.js');
router.get('/user/login', async ctx => {
ctx.body = JSON.parse(fs.readFileSync( './pass.json'));
console.log(ctx.body);
});
router.post('/signin', async (ctx, next) => {
var
name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log(`signin with name: ${name}, password: ${password}`);
if (name === 'koa' && password === '12345') {
ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed!</h1>
<p>Try again</p>`;
}
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(8090, () => {
console.log('The server is running at http://localhost:' + 8090);
});
koa:2.52
koa-bodyparse:4.21
koa-router:7.4
when I type http://localhost:8090/user/login can get the Json data,but type http://localhost:8090/signin always show 405 Methods Not Allowed ,(debian firefxo) show Request Method "GET",response Allow: POST,Connection: "keep-alive"
I hope get your help.
I guess you shouldn't use the chrome to do the post cause when you type some url, the default method is GET not POST, you can check it out from the NETwork。 Try postman it will work.Sorry for my bad english,I hope it will help XD

Can't use Express to send data back to client more than once

In my app, I send a post request to the server with data containing a CSV file:
$.ajax({
type:"POST",
contentType: "application/json",
url:"/",
data: JSON.stringify({fileData:My_CSV_FILE}),
success: function(csvJson) {
console.log('in the done block!');
//can use csvJson in this handler
});
});
Note: I'm posting to the home route, and I am able to get a response with the data converted from the server. The problem is that whether I run on localhost or Heroku, I am only able to trigger the POST request once, then I have to restart the server (even if I refresh the page). So I know the issue is with my route somewhere:
UPDATED TO INCLUDE FULL SERVER FILE:
'use strict';
const express = require('express');
const csvtojson = require('csvtojson');
const PORT = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const Converter = require('csvtojson').Converter;
var converter = new Converter({});
let app = express();
app.use(bodyParser.json({limit: '300kb'}));
app.use(express.static(__dirname +'/public'));
app.post('/',function(req,res) {
var csvFile = (req.body.fileData);
converter.fromString(csvFile, function(err, result) {
if(!err) {
console.log(result);
res.json(result);
}else {
res.json({error: 'Could not convert'});
}
})
});
app.listen(PORT, () => {
console.log(`app listening on port ${PORT}`);
});
I'm using Express 4. Again, everything works, but only once. When I run Heroku logs, or check the console on localhost I get:
Error: Can't set headers after they are sent.
But I don't understand how I'm re-setting them.
If wanting to run on localhost, here is a link to the projects github: https://github.com/qctimes/calendar_export
You should move the converter instantiation to be done inside the app.post callback method. This way it will instantiate a new object at every request.
This is is how your code should be:
'use strict';
const express = require('express');
const csvtojson = require('csvtojson');
const PORT = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const Converter = require('csvtojson').Converter;
let app = express();
app.use(bodyParser.json({limit: '300kb'}));
app.use(express.static(__dirname +'/public'));
app.post('/',function(req,res) {
var csvFile = (req.body.fileData);
var converter = new Converter({}); // instantiation is done here
converter.fromString(csvFile, function(err, result) {
if(!err) {
console.log(result);
res.send(result);
}else {
res.send({error: 'Could not convert'});
}
});
});
app.listen(PORT, () => {
console.log(`app listening on port ${PORT}`);
});

Node JS works on localhost, online 404

So i am trying to publish an node js app , but it is returning me 404 for my post calls . It works perfectly on localhost. This is my code :
app.js
var express = require('express');
var path = require('path');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var server = require('http').Server(app);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, '/')));
app.use('/', routes);
app.use('/users', users);
server.listen(process.env.PORT || 3000,function(){
console.log("Working on " + process.env.PORT);
});
module.exports = app;
This is my routes index.js
var express = require('express');
var request = require('request');
var path = require('path');
var bodyParser = require('body-parser');
var router = express.Router();
var app = express();
var jsonParser = bodyParser.json()
app.use(bodyParser.json())
var Connection = require('tedious').Connection;
var databaseConnection
var config = {}
var Connection = require('tedious').Connection;
var config = {
userName: 'asdasd',
password: 'password',
server: 'server',
options: {encrypt: true, database: 'asdasd'}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
console.log("Connected");
});
router.post('/call',jsonParser, function(req,res){
res.send('someresponse')
}
I am simply calling /call through ajax , but it keeps throwing 404 not found.
What am i doing wrong ? It doesnt make sense to me to work on localhost but not online.
If you are using express you cann start server directly with express.
app.listen(port)
If you want to do it with nodejs http you also have to set the port nodejs should listen to.
nodejs http
express app.listen
The problem was my auto generated web config was not doing its job , i have swaped it with another one i found on internet
https://github.com/projectkudu/kudu/wiki/Using-a-custom-web.config-for-Node-apps
Just changed from server.js to app.js

Resources