app.post not working! "Cannot GET /up" - javascript

i have a button in a /index.jade file that when pressed it executes
window.location.replace("https://upload-andsize.glitch.me/up") function.
the only thing it does is to redirect me from / to /up so far so good.
and if i make a get request all works fine but!..
a post request will not work
app.post("/up",function(req,res){
res.send("hello-world")
})
//will return Cannot GET /up
server code
var express = require('express'),
app = express();
app.set("view engine","jade")
app.use(express.static('public'));
app.get("/",function(req,res,next){
res.render(__dirname+"/views/index.jade",{})
next()
})
app.post("/up",function(req,res){
res.send("hi")
})
var listener = app.listen(process.env.PORT || 3000, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
jade code
html
script(src= "client.js")
title!=title
h1 upload a file and see its weight
input(type="file" id="myfile")
input(type="button" onClick="send()" value="submit")
client code
function send(){
window.location.replace("https://upload-andsize.glitch.me/up")
}

ok the problem was a lack of understanding how does the routs work
the solution is that im not sending a post request but a get request
thats why im getting an error
changed the html to
form(action="/up" method="POST")
input(type="file" id="myfile")
input(type="submit" value="submit")
and it all work well hope it will help others in future

Please add app.get('/up',(res,req)=>{}) method in your server code.

Related

Forward messages to another number using Twilio

I would like to forward all incoming messages to some other number with the number to which I got the reply on Twilio,
For example:
I have a Twilio number say "+14444444444" to which I got the reply from number say: '+15555555555' and I would like to forward all messages to number '+19999999999'.
So I would like to forward all messages on number '+19999999999' which should be received from '+15555555555', not from '+14444444444',
Will anyone please let us know if there is an API in Twilio that can do a trick using nodeJs.
Note: The SMS forwarding number can be dynamic and in that case, we cannot use Twiml, if we can use Twiml so please let us know how to set dynamic forwarding number.
Also got the following link that says how to forward SMS but is not relevant to approach we are trying to accomplish using nodeJS:
https://support.twilio.com/hc/en-us/articles/223134287-Forwarding-SMS-messages-to-another-phone-number
Thanks, any help will be appreciated.
Updated Answer
Thanks, #Alex and #Piyush for clarifying the question:
Really sorry about that! Thanks for clarifying. If I understand you correctly now, you want to forward a message to another number, but preservice the original number from the message. Unfortunately, there's not a way to do this. You can forward the message and include the original sender in the message body, but there's no way to replace the actual sender as the original.
Let me know if I understood that correctly this time and if there's anything else I can help with.
Old Answer (Message forwarding with own number)
You can use TwiML dynamically when using our helper libraries, so that should be something you can setup using Node. When your webhook sends your message to your Node application, you can check the body of the message, and make a conditional SMS request or conditionally point to different TwiML based on the content of the body. Here's an example of how to setup a conditional reply for your incoming messages based on the message body in Node:
https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-node-js
While this example is for replying to messages, it shows you the principles of how conditional TwiML can work.
You would just have add a "to" number you want to forward the message to in the message request.
Below is the example of conditional forward.
const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', (req, res) => {
const twiml = new MessagingResponse();
twiml.to = "+1234567890 // Your number here.
if (req.body.Body == 'hello') {
twiml.message('Hi!');
} else if (req.body.Body == 'bye') {
twiml.message('Goodbye');
} else {
twiml.message(
'No Body param match, Twilio sends this in the request to your server.'
);
}
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(twiml.toString());
});
http.createServer(app).listen(1337, () => {
console.log('Express server listening on port 1337');
});
Let me know if that helps and if you have anymore questions on how to set this up.

Socket.io: io is not defined

So, I am trying to get data on my node.js file instead of directly getting it on my JS file.
I a using Socket.io 2 here, Below is a snapshot of my code and this is also the first time I am using Websocket with Node.
I am doing something like
var socket = require('socket.io')
//Home Page
app.get("/", function(req, res) {
var cryto = io.connect("https://xyfz.com/);
cryto.on('trades', function (tradeMsg) {
console.log(tradeMsg);
});
res.render("index");
});
I also tried something like
var io = socket("https://abc.io/");
and
var socket = require('socket.io')
var io = socket();
which was throwing errors like server.listeners is not a function and io.connect is not a function.
I am certain that I messing up stuff here so can someone guide me about the correct way of doing it?
Two things which are wrong .
First Consider using Socket.io-client instead of Socket.io.
Second and very much important.
Never ever make API calls inside your routes. This will trigger a API call everytime user opens your website or webpage
You can also expect an error "Unexpected headers" or something like that.
Always, Try do declare it outside any routes in your NodeAPP.
Same goes for socket.io as well

Run a server side Javascript version with Express

recently i got into web programming and i started to learn javascript,node.js and express.js and my goal is to run a server side javascript function(to be more accurate a function to search something in a mysql db) when a button got pressed on a html.
My dir structure is like this : A main dir, containing a dir "page". Page containing server.js, dbFunctions.js and "public" dir. Public containing a index.html,style.css and some images.
Server.js :
var express = require('express');
var app = express();
var path = require('path');
var port = 8888;
//allow to use static files
app.use(express.static("public"));
//start server
app.listen(port);
console.log("Server running on port" + port);
HTML Example
<html>
<head>
<title>Test html</title>
</head>
<label for="key">Valid key:
<input id="key" name="key" required>
</label>
<input type="checkbox" name="test" value="testval" checked>
<button type="button">Button</button>
</html>
So basically the HTML got a input field,a checkbox and a button, and if the button is clicked it should run a function from dbFunctions.js with parameter(taken from the field and the checkbox as bool) on server side
I heard something about ajax calls etc but those explanations are usually very confusing. Is there any "hello world" example?
Greetings.
Sounds like you're quite new to JS so I would recommend breaking this down into two components.
One is your server side code and the other is your front end code. As you mentioned you find the front end code confusing, I would suggest coming back to that, once you have got your server side code working.
To make things easy, you could use something like express generator which boiler plates everything for you.
You can then follow this guide which will show you how you can set up a route which you will be able to make some sort of request to. Like a POST, GET or PUT request (which is what your front end AJAX code will eventually make a call to).
My advice would be to try get your route working and testing it with something like Postman so you don't have to worry about building the front end simultaneously.
When you are happy with the back end, you can start look into how to make requests from the browser to hit your new back end route you have set up.
Yes, check out this amazing post
https://medium.com/#adnanrahic/hello-world-app-with-node-js-and-express-c1eb7cfa8a30
This is an example hello world node js application with express js.
First you need to make your html page call your server. To do that you can :
Place your button inside a form and set your form action equal to /getHelloWorld
Create a javascript script and call your /getHelloWorld in ajax
In your server you need to catch route like this :
Server.js :
var express = require('express');
var app = express();
var path = require('path');
var port = 8888;
//allow to use static files
app.use(express.static("public"));
app.get('/getHelloWorld', (req, res) => {
res.send('hello world !');
});
//start server
app.listen(port);
console.log("Server running on port" + port);
with this your server will return Hello World When you'r calling this road : /getHelloWorld.
Then you just need to replace code inside route catch by a code to call your DB and return your DB response.

Error NodeJS : Cannot get

I'll try to be as clear as I can be. So I'm trying to make a little plateform. I would like that someone connect to the page (in localhost) and then, have the possibility to click on a button, and this button will redirect him to another html page.
So I have a project folder with my "initial" html, my app.js file, and the other html file, which should show itself when clicking on the button.
The server works like this :
var application = require('express')(),
server = require('http').createServer(application),
io = require('socket.io').listen(server),
ent = require('ent'),
fs = require('fs');
application.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
and then, I have the button :
<input type="button" value="blah">
When launching "node app.js" on the terminal, I go on the page, click on the the button and then I got the error "Cannot GET /pfc.html".
Sorry if I'm quite not understandable, I hope someone will understand me.
Thanks and have a nice day!!
You wrote some code to tell your server what to do if the browser asks for /
application.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
Then you wrote a link:
<a href="pfc.html"
which makes the browser ask for /pfx.html.
You haven't written anything in the server side code to tell it how to respond to a request for that. You've only told it how to respond to a request for /.
You could write something similar (application.get('/pfx.html',...) or find some existing middleware for handling static files.
If you have multiple HTML files like pfc.html, you can use
application.use(express.static('public'));
and keep all your html files (including pfc.html) in a folder named public and all those html files that you serve like:
you can look for them at public/pfc.html and such. If the file exists, then the application won't return stuff like Cannot GET /pfc.html and you won't need to write explicit routes for all of them.

Updating data realtime in Node.js express website

I'm trying to achieve something what I think should be very simple to do, but all the tutorials and examples I find seem to be an overkill.
What I am doing:
I'm fetching weather info periodically, and I want to update the text on the website everytime its fetched without user having to refresh the browser.
Almost every tutorial on realtime data updating recommends using socket.io and I have given it a try, but I can't get it to do what I want and I'm starting to think that there should be an easier way and that socket.io might not be the best way to go about this. Any suggestions? How do I get simple line of text update on website without user having to refresh the page?
My weather script:
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
function refreshWeather() {
var temperature = getTemperature();
io.sockets.emit('broadcast', {
temperature : temperature
});
}
My jade script:
doctype html
html
head
link(rel='stylesheet', href='/css/index.css')
title Dashboard
body
script(src='/socket.io/socket.io.js')
script.
var socket = io();
socket.on('broadcast', function (data) {
// UPDATE WEATHER HERE
});
.main-content
h1 Weather is: // I WANT THIS TO BE UPDATED
You could:
Get rid of socket.io.
Make an end point for retrieving the temperature.
Do some polling on the frontend.
Backend would look something like this:
var express = require('express');
var app = express();
var server = require('http').Server(app);
app.get('/weather', function (req, res) {
res.send(getTemperature())
});
Frontend would look something like this:
doctype html
html
head
link(rel='stylesheet', href='/css/index.css')
title Dashboard
body
.main-content
h1(id='weather') Weather is: // I WANT THIS TO BE UPDATED
script.
setInterval(function () {
fetch('/some/url', {
method: 'get'
}).then(function(response) {
// UPDATE WEATHER HERE
document.getElementById('weather').innerHTML = response
}).catch(function(err) {
// Error :(
});
}, 1000) // milliseconds
Code is totally untested, so please try not to copy and paste — adapt it instead. Also, if you're going to use the fetch API, you might want to use a polyfill, otherwise, just use plain ajax.

Categories