Hi I'm learning the mean stack on cloud9.
I've come to the point where I'm trying to send variables to my node.js server but I'm not sure if my server is picking it up. Are there any obvious errors with my post request code?
app.js(frontend angular)
console.log('begin');
var http = new XMLHttpRequest();
var params = "text=stuff";
http.open("POST", "https://new-backup.splacorn.c9.io/myApp/server/server.js/", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
console.log('onreadystatechange');
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
else {
console.log('readyState=' + http.readyState + ', status: ' + http.status);
}
}
console.log('sending...')
http.send(params);
console.log('end');
this is the console response that I am getting:
begin
sending...
end
POST https://new-backup.splacorn.c9.io/myApp/server/server.js/ net::ERR_INSECURE_RESPONSE$scope.addNewUser
onreadystatechange
readyState=4, status: 0
I believe that the error that I am getting is attributed to this line:
http.open("POST", "https://new-backup.splacorn.c9.io/myApp/server/server.js/", true);
once http.send(params); calls it.
Here is the server.js file (backend)
var express = require('express');
var fs = require('fs');
var app = express();
var bodyParser = require('body-parser')
app.use(express.bodyParser());
app.post('/', function(req, res){
console.log('POST /');
res.writeHead(200);
res.end('this is from the server');
});
var port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port);
Does anyone know why I'm getting the error? Part of me thinks that I'm getting the cloud 9 server url wrong but I'm not sure... If anyone can help me figure this out that would be amazing!
I'd like to use socket.io instead.
Here's a small example of how you can do it:-
Client side code:
var io = io("http://localhost:1337");
io.emit('give me some data',{test:'testing socket.io'});
io.on('got the data',function(data){
console.log(data.test);
});
Server side code:
var app = require('express').createServer();
var io = require('socket.io')(app);
io.on('connection',function(socket){
socket.on('give me some data',function(data){
socket.emit('got the data',data);
}
app.listen(1337);
You can get socket.io here
They have both client side as well as server side code. Hope you got my point. I was at phone so couldn't type much. And also, socket.io provides real time connection between the client and the server :)
Related
I just want to extract an http-Post but I didn't get it working. Can somebody help me please? The request is made by my HTML Frontend using XMLHttpRequest() and the backend is node.js. When I send the request I only get an empty Object {}
Node Backend
var express = require('express');
const bodyParser = require('body-parser');
var app = express();
app.use(express.json());
app.post('/save_options', (req, res) => {
console.log(req.body);
res.sendStatus(200);
});
Frontend
let DATA_FRONTEND_OPTIONS = {
"test":"1"
}
function save_options_to_database() {
var do_it_async = true;
var request = new XMLHttpRequest();
request.onload = function () {
var status = request.status;
var data = request.responseText;
}
request.open("POST", "/save_options", do_it_async);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
//request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request.send(JSON.stringify(DATA_FRONTEND_OPTIONS));
}
Simply add
app.use(express.urlencoded());
to your express configuration.
Here is great explanation:
https://stackoverflow.com/a/51844327/8522881
You have to add express.json() and express.urlencoded() for POST request.
Example:
app.use(express.json());
app.use(express.urlencoded());
Because in POST request the data which is sending is in form of some type of data object and you have to tell the server to accept or store that type of data (object), which is enclosed in the body of your POST request.
Above the same solution applied for PUT requests also.
im trying to do a simple ajax call but somehow it doesnt work.I cant figure it out, would be nice if someone could help me.
Server script :
var express = require('express');
var app = express();
var path = require('path');
var port = 8888;
//allow to use static files
app.use(express.static("public"));
//listen to smth
app.get('/test1', function (req, res) {
res.send('GET request to the homepage');
});
//start server
app.listen(port);
console.log("Server running on port" + port);
HTML Button that runs a client based JS
<button onclick="callServerSideScript('key','port','address','username','password','gem','proxy','crypt')" type="button" id="build">Get build</button>
Client based JS :
function callServerSideScript(key,port,address,username,password,gem,proxy,crypt){
keyVal = document.getElementById(key).value;
portVal = document.getElementById(port).value;
addressVal = document.getElementById(address).value;
userVal = document.getElementById(username).value;
pwVal = document.getElementById(password).value;
gemVal = document.getElementById(gem).checked;
proxyVal = document.getElementById(proxy).checked;
crytpVal = document.getElementById(crypt).checked;
httpRequest = new XMLHttpRequest();
httpRequest.open('POST', '/test1');
httpRequest.send('some data');
}
Normally it should do a /test1 request to the server and the server should react to it? I am missing something?
eighter do httpRequest.open('GET', '/test1'); (client) or app.post('/test1', handler); (server). but if your sending a POST request and the server expects a GET request it just gets 404'd
i want to send some json data from my client page to server page of node.js,
here i have my server page :
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(req,res){
res.send('recieved request');
console.log(req.body);
});
app.listen(8081);
console.log('listening on 8081');
client page:
var name ='someName';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState== 4 && this.status == 200){
console.log(this.responseText);
}
};
xhttp.setRequestHeader({'Content-Type': 'application/json'});
xhttp.open('POST', 'http://localhost:8081', true);
xhttp.send(JSON.stringify({'name' : name}));
I got the result as a null json {}.
NOTE: I don't want to about submission of a form , i just want to send JSON data from html file to node.js file.
The correct signature for a call to XMLHTTPRequest#setRequestHeader is setRequestHeader(header, value);
Change
xhttp.setRequestHeader({'Content-Type': 'application/json'});
to
xhttp.setRequestHeader('Content-Type', 'application/json');
Docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
I am currently working with the Express platform, the Twilio Node.js SMS API and obviously javascript to send text messages to my users. Problem is, I don't know what I should do in order to send data through my GET variables on the front-end and capture those values with node.js on the back-end.
For testing purposes, I created a simple button that sends a text message to a fixed number when clicked.
Here is the javascript side:
function sms() {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:5001", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
}
Here is the node.js side:
var accountSid = 'ACCOUNT_SID';
var authToken = 'ACCOUNT_TOKEN';
//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);
var express = require("express");
var app = express();
app.get('/',function(request,response){
var to = "TO";
var from = "FROM";
client.messages.create({
to: to,
from: from,
body: 'Another message from Twilio!',
}, function (err, message) {
console.log("message sent");
});
});
app.listen(5001);
I have came across two ways to send a responseText from Node.js, but can't manage to make them work
first one using response.send("Hello World"); or the second one response.write("Hello again"); response.end();
So just to sum it up, I want to send variables (to, from, message, etc.) through my http request, capture them in node.js and send a responseText! As a heads up, I'm very comfortable with AJAX requests between JS and PHP, but Node.js is new to me.
Thanks in advance
I think the new Guides will help you out here with How to receive and reply to SMS in Node.js:
https://www.twilio.com/docs/guides/sms/how-to-receive-and-reply-in-node-js
The CodeRail along the right hand side will walk you through it step-by-step but you should pay attention particularly to the section titled "Generate a dynamic TwiML Message".
var http = require('http'),
express = require('express'),
twilio = require('twilio'),
bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function(req, res) {
var twilio = require('twilio');
var twiml = new twilio.TwimlResponse();
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, function () {
console.log("Express server listening on port 1337");
});
I am trying to implement a node http proxy for the first time with my simple twitter tweeter. I have never used this before and tried following the docs (https://github.com/nodejitsu/node-http-proxy) with no luck. Can anyone point me in the right direction? Also, is it okay to run this locally on a mac? Thanks
var express = require('express');
var app = express();
var port = 8300;
var twitter = require('twitter');
var twit = new twitter({ keys and stuff })
var http = require('http'),
httpProxy = require('http-proxy');
twit.post('statuses/update', {status: "Hello world!"}
//this works
httpProxy.createProxyServer({target:'http://localhost:3000'}).listen(3000);
// Create your target server--- WHat exactly does this mean??
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(3000);
You should not use this lib for proxing you request. This lib is for make your own proxy server. Look at example how to use proxy with twitter lib