The problem I currently have is that when I send my form data in React using axios or even without it I am unable to retrieve my data on the backend side using express. I am viewing the request received on the back end console but am unable to access it via code. React code is via Node on port 3000, Express on 3001. Application was created using create-react-app, here is a picture:Problem
Project Structure:
cssd -> Where I run npm start launching back end
cssd/routes/ -> Where users.js is located with the routes to obtain code
cssd/client/ -> Where i run npm start launching front end
cssd/client/src/setupProxy.js -> where my proxy route is
I've already tried creating a setupProxy.js file as well as numerous get / post methods trying to receive the data and any of the info available on stack has been searched as well but if I've missed something please let me know. Even with a console.log at the base, i still can't receive it.
Within setupProxy:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/routes/*',
{ target: "http://localhost:3001/" }
));
}
Within client's App.js / React:
render() {
return (
<form id="contact-form" onSubmit={this.handleSubmit.bind(this)} method="POST">
<div className="form-group">
<label htmlFor="name">Name</label>
<input type="text" className="form-control" id="name"/>
</div>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email address</label>
<input type="text" className="form-control" id="email" aria-describedby="emailHelp"/>
</div>
<div className="form-group">
<label htmlFor="message">Message</label>
<textarea className="form-control" rows="5" id="message"></textarea>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
)
}
handleSubmit(e)
{
e.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const message = document.getElementById('message').value;
var inputData = {name, email, message};
fetch('/routes/users',
{
method: 'POST',
body: inputData
})
alert("sent data");
this.resetForm();
}
Within routes/users.js / Express code:
var express = require('express');
var router = express.Router();
const bodyParser = require("body-parser");
const app = express();
app.use(
bodyParser.urlencoded({ // basically any extra characters
extended: true
}),
bodyParser.json()
);
// Re-directs, ex entered in nothing, go to get
router.get("/routes/users", function(req, res) {
console.log("HERE 1 !");
var name = req.body.name;
var email = req.body.email;
var message = req.body.message;
console.log("The data: ", name, email, message);
});
router.post("/routes/users", function(req, res) {
console.log("HERE 2 !");
var name = req.body.name;
var email = req.body.email;
var message = req.body.message;
console.log("The data", name, email, message);
});
app.get("/routes/users", function(req, res) {
console.log("HERE 3 !");
var name = req.body.name;
var email = req.body.email;
var message = req.body.message;
console.log("The data: ", name, email, message);
});
app.post("/routes/users", function(req, res) {
console.log("HERE 4 !");
var name = req.body.name;
var email = req.body.email;
var message = req.body.message;
console.log("The data", name, email, message);
});
router.get("routes/users", function(req, res) {
console.log("HERE 5 !");
var name = req.body.name;
var email = req.body.email;
var message = req.body.message;
console.log("The data: ", name, email, message);
});
router.post("routes/users", function(req, res) {
console.log("HERE 6 !");
var name = req.body.name;
var email = req.body.email;
var message = req.body.message;
console.log("The data", name, email, message);
});
app.get("routes/users", function(req, res) {
console.log("HERE 7 !");
var name = req.body.name;
var email = req.body.email;
var message = req.body.message;
console.log("The data: ", name, email, message);
});
app.post("routes/users", function(req, res) {
console.log("HERE 8 !");
var name = req.body.name;
var email = req.body.email;
var message = req.body.message;
console.log("The data", name, email, message);
});
const port = 3000;
//console.log(`Back end is listening on port ${port}`);
app.listen(port, () => console.log(`Back end is listening on port ${port}`));
module.exports = router;
The expected results should be that I receive a console.log from one of the functions and can then work with my code from there but I'm just unable to get any of them to be called. Only thing shown in the console is on the back-end side receiving the request
Remove all proxying from the server as this is only if you are serving the client and server from the same host and port. So make sure your app.listen is on a different port than your client like so.
const port = process.env.PORT || 5000
app.listen(port, () => console.log(`listnening on ${port}`));
Is this app set up with Create React App? If so you can add a proxy to the package.json of the client (React)
"proxy": "http://localhost:5000"
Create react app uses webpack dev server to serve your app to the browser. You can use a proxy from your client to achieve want you want.
In your package.json of your react app, add "proxy": "http://localhost:3001"
Here is more info about this from the create react app docs.
Your backend code does not need any changes to make this work, in fact I would even remove all proxy setup code in your backend. Only thing needed is to add this one setting in your react app package.json.
Related
I am trying to post to my api endpint, I get the error:
Uncaught (in promise) Error: Network Error
at createError (C:\sites\LYD\node_modules\axios\lib\core\createError.js:16)
at XMLHttpRequest.handleError (C:\sites\LYD\node_modules\axios\lib\adapters\xhr.js:87)
My axios post is:
submitForm(UserDetails) {
let self = this;
self.show();
axios
.post('http://localhost:3001/api/users', UserDetails)
.then(function(response) {
self.hide();
});
}
My node error is:
C:\sites\LYD>node server
api running on port 3001
(node:11808) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
events.js:160
throw er; // Unhandled 'error' event
^
TypeError: First argument must be a string or Buffer
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:555:11)
at C:\sites\LYD\server\index.js:75:20
at C:\sites\LYD\node_modules\mongoose\lib\model.js:3809:16
at C:\sites\LYD\node_modules\mongoose\lib\services\model\applyHooks.js:164:17
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
Any ideas?
My server.js is:
//first we import our dependencies...
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const User = require('../models/users');
//and create our instances
const app = express();
const router = express.Router();
//set our port to either a predetermined port number if you have set it up, or 3001
const port = process.env.API_PORT || 3001;
//db config -- REPLACE USERNAME/PASSWORD/DATABASE WITH YOUR OWN FROM MLAB!
const mongoDB =
'mongodb://dxxx#aws-eu-west-1-portal.4.dblayer.com:10204/xxx?ssl=true';
mongoose.connect(mongoDB, { useMongoClient: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//now we should configure the APi to use bodyParser and look for JSON data in the body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//To prevent errors from Cross Origin Resource Sharing, we will set our headers to allow CORS with middleware like so:
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader(
'Access-Control-Allow-Methods',
'GET,HEAD,OPTIONS,POST,PUT,DELETE'
);
res.setHeader(
'Access-Control-Allow-Headers',
'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
);
//and remove cacheing so we get the most recent comments
res.setHeader('Cache-Control', 'no-cache');
next();
});
//now we can set the route path & initialize the API
router.get('/', function(req, res) {
res.json({ message: 'API Initialized!' });
});
//adding the /comments route to our /api router
router
.route('/users')
//retrieve all comments from the database
.get(function(req, res) {
//looks at our Comment Schema
User.find(function(err, users) {
if (err) res.send(err);
//responds with a json object of our database comments.
res.json(users);
});
})
//post new comment to the database
.post(function(req, res) {
var NewUser = new User();
req.body.accessCode ? (NewUser.accessCode = req.body.accessCode) : null;
req.body.age ? (NewUser.age = req.body.age) : null;
req.body.drinkConcern
? (NewUser.drinkConcern = req.body.drinkConcern)
: null;
req.body.drinkOften ? (NewUser.drinkOften = req.body.drinkOften) : null;
req.body.ethnicity ? (NewUser.ethnicity = req.body.ethnicity) : null;
req.body.gender ? (NewUser.age = req.body.gender) : null;
req.body.language ? (NewUser.language = req.body.language) : null;
NewUser.save(function(err) {
if (err) res.end(err);
res.json({ message: 'Comment successfully added!' });
});
});
//Adding a route to a specific comment based on the database ID
router
.route('/users/:id')
//The put method gives us the chance to update our comment based on the ID passed to the route
.put(function(req, res) {
Comment.findById(req.params.id, function(err, user) {
if (err) res.send(err);
//setting the new author and text to whatever was changed. If nothing was changed
// we will not alter the field.
req.body.author ? (comment.author = req.body.author) : null;
req.body.text ? (comment.text = req.body.text) : null;
//save comment
user.save(function(err) {
if (err) res.send(err);
res.json({ message: 'Comment has been updated' });
});
});
})
//delete method for removing a comment from our database
.delete(function(req, res) {
//selects the comment by its ID, then removes it.
User.remove({ _id: req.params.comment_id }, function(err, user) {
if (err) res.send(err);
res.json({ message: 'Comment has been deleted' });
});
});
//Use our router configuration when we call /api
app.use('/api', router);
//starts the server and listens for requests
app.listen(port, function() {
console.log(`api running on port ${port}`);
});
I have changed my axios post to this:
let self = this;
self.show();
const headers = {
'Content-Type': 'application/json',
};
axios
.post('http://localhost:3001/api/users', UserDetails, headers)
.then(function(response) {
self.hide();
});
You can change the mongoose query to,
let query = {} //or any other query
User.find(query,function(err,res){
...
})
I think the problem is with your routes.
When you create a route instead of using router.route('/route').post(function(req, res) { ... }, use router.post('/route', function(req, res) { .... } (obviously change .post to the method you want to use)
In your code this would be:
router
.get('/users', function(req, res) {
User.find(function(err, users) {
if (err) res.send(err);
res.json(users);
});
})
I think you can only do app.route('/route').get(...).post(...) but not with router
Look at the express routing documentation for more info: https://expressjs.com/en/guide/routing.html
Edit: NEVERMIND - I made a small mistake in the Angular service. My bad.
I'm trying to teach myself more backend by building a simple CMS using angular, Node and Express, and PostgreSql. I figured out how to do achieve all the CRUD functionality except UPDATE. I thought I understood what to do but I can't figure out where I'm going wrong. I keep getting a 404. What am I misunderstanding or going about the wrong way? I know this is simple but I'm pretty new so any help in understanding where I'm getting confused is really appreciated. Here's the relevant code:
HTML
<form ng-submit="updateBlogEntry(specificBlog.id, specificBlog.title, specificBlog.author, specificBlog.imageurl, specificBlog.content)">
<h2>Title:</h2>
<input type="text" ng-model="specificBlog.title"></input>
<br>
<h3>Author:</h3>
<input type="text" ng-model="specificBlog.author"></input>
<br>
<h3>Photo:</h3>
<input type="text" ng-model="specificBlog.imageurl"></input>
<br>
<h3>Content:</h3>
<textarea type="text" rows="5" cols="50" ng-model="specificBlog.content">
</textarea>
<br>
<button type="submit">Save Changes</button>
</form>
Angular Controller
var id = $stateParams.id;
var title = $stateParams.title;
var author = $stateParams.author;
var imageurl = $stateParams.imageurl;
var content = $stateParams.content;
$scope.updateBlogEntry = function(id, title, author, imageurl, content) {
adminService.updateBlogEntry(id, title, author, imageurl, content);
}
Angular Service
this.updateBlogEntry = function(id, title, author, imageurl, content) {
return $http({
method: 'PUT',
url: 'updateBlogEntry/' + id,
data: {
id: id,
title: title,
author: author,
imageurl: imageurl,
content: content
}
})
.success(function(data) {
alert("Entry Updated");
})
.error(function(data) {
alert("Error Updating");
})
Server Index
// EXTERNAL MODULES //
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var massive = require('massive');
// CONFIG //
var config = require('./config');
// EXPRESS //
var app = module.exports = express();
app.use(express.static(__dirname + './../dist'));
app.use(bodyParser.json());
// MASSIVE //
var massiveUri = config.MASSIVE_URI;
var massiveServer = massive.connectSync({
connectionString: massiveUri
});
app.set('db', massiveServer);
var db = app.get('db');
var dbSetup = require('./services/dbSetup');
dbSetup.run();
// CONTROLLERS //
var userCtrl = require('./controllers/userCtrl');
var blogCtrl = require('./controllers/blogCtrl');
// Blog Endpoints //
app.post('/api/createBlogEntry', blogCtrl.createBlogEntry);
app.get('/api/getBlogEntries', blogCtrl.readBlogEntries);
app.get('/api/getBlogEntry/:id', blogCtrl.readBlogEntry);
// BUG Why isn't this working?
app.put('/api/updateBlogEntry/:id', blogCtrl.updateBlogEntry);
// CONNECTIONS //
var port = config.PORT;
app.listen(port, function() {
console.log('Listening on port ' + port);
});
Node Controller
updateBlogEntry: function(req, res, next){
db.blogs.blog_update([
req.params.id,
req.body.title,
req.body.author,
req.body.imageurl,
req.body.content
],
function(err, results){
if (err){
console.error(err);
res.send(err);
} else {
res.send(results[0]);
}
})
}
blog_update.sql
UPDATE blogs
set
title = COALESCE($2, title),
author = COALESCE($3, author),
imageurl = COALESCE($4, imageurl),
content = COALESCE($5, content)
WHERE id = $1
RETURNING * ;
The error in the console:
angular.js:11881 PUT http://localhost:3000/updateBlogEntry/1 404 (Not Found)
You have written your URL wrong.
It should be /api/updateBlogEntry as per your Node's express routes.
change this part
` url: 'updateBlogEntry/' + id,`
It should be
url: '/api/updateBlogEntry/' + id,
I am trying to post my form data to my database. When I click the submit button nothing happens. It should be calling my addDiscovery method in the discoverCtrl, but it just does nothing. I am getting no errors and have watched several tutorials in which (to me) I don't see the difference in my code and what is presented. Please tell this Angular noob what he is doing wrong!...Thanks in advance.
discoverCtrl.js:
angular.module('app')
.controller('discoverCtrl', ['$scope', '$http', function($scope, $http, $log) {
$scope.title = "Discover It!";
$scope.objects = ['animal', 'art', 'food', 'landform', 'object', 'plant', 'pokemon', 'vehicle'];
this.discovery = {};
$scope.addDiscovery = function() {
this.discovery.image = "";
this.discovery.location = ""/*gps api call*/;
this.discovery.discoveredOn = Date.now();
console.log("I'm posting something maybe?");
$http.post('/discover', {discovery: this.discovery}).success(function(data) {
});
this.discovery = {};
};
}]);
discover.html:
<h1>{{title}}</h1>
<form name="discoverForm" ng-controller="discoverCtrl" ng-submit="discoverForm.$valid && discoverCtrl.addDiscovery" novalidate>
<input ng-model="discoverCtrl.discovery.name" type="text" class="form-control" placeholder="What is the name of your discovery?" title="name" required />
<select ng-model="discoverCtrl.discovery.objectType" class="form-control" ng-options="object for object in objects" title="objectType" required>
<option value="" disabled selected>Select what type of discovery you have found.</option>
</select>
<textarea ng-model="discoverCtrl.discovery.description" class="form-control" placeholder="What does your discovery look/feel/smell like? Are there any other observations or knowledge you can share about it?" title="description" required></textarea>
<!--location found by gps TODO-->
<div>Discovery is {{discoverForm.$valid}}</div>
<input type="submit" ng-click="discoverCtrl.addDiscovery" class="btn btn-primary pull-right" value="Discover It!" />
</form>
server.js (sorry for the length. The route is at the bottom, but I didn't know if it could have been something else in here as well so I wanted to include it.):
// requires express and body-parser
var express = require('express');
var bodyParser = require('body-parser');
var expressSessions = require('express-session');
var logger = require('morgan');
var passport = require('passport');
// Google oauth2 login, key, and secrets
var GoogleStrategy = require('passport-google-oauth20').Strategy;
var configAuth = require('./auth');
// OAuth 2.0-based strategies require a `verify` function which receives the
// credential (`accessToken`) for accessing the Facebook API on the user's
// behalf, along with the user's profile. The function must invoke `cb`
// with a user object, which will be set at `req.user` in route handlers after
// authentication.
passport.use(new GoogleStrategy(configAuth.googleAuth,
function(accessToken, refreshToken, profile, cb) {
console.log('access token is', accessToken)
return cb(null, profile);
}));
// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session. In a
// production-quality application, this would typically be as simple as
// supplying the user ID when serializing, and querying the user record by ID
// from the database when deserializing.
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
//requiring and setting up mongo database/collections
var mongojs = require('mongojs');
var databaseUrl = "discoverIt";
var collections = ["users", "discoveries"];
// creates a databse in mongo called scrape with two collections: articles and comments
var db = mongojs('discoverIt', ['users', 'discoveries']);
// lets us know if there is an error with the database if it doesn't turn on
db.on('error', function(err) {
console.log('Database Error: ', err);
});
// creating an instance of express
var app = express();
// assigning the port or using the PORT environment variable
var PORT = process.env.PORT || 3000;
// makes static content in assets accessible
app.use(express.static(__dirname + '/public'));
// // BodyParser interprets data sent to the server
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));
// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());
// Define routes.
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});
app.get('/login',
function(req, res){
res.sendFile(__dirname + '/public/views/login.html');
});
app.get('/login/google',
passport.authenticate('google', {scope: 'profile'}));
app.get('/login/google/return',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/profile');
});
app.get('/profile',
require('connect-ensure-login').ensureLoggedIn(),
function(req, res){
db.users.insert({
"email": "",
"avatar": req.user.photos[0].value,
"userName": req.user.displayName,
"discoveries": 0,
"edits": 0,
"confirms": 0,
"points": 0
});
res.send({ user: req.user });
});
app.post('/discover', function(req, res){
db.discoveries.insert({
"user": req.user.displayName,
"userId": req.user.id,
"image": req.body.discovery.discovery.image,
"name": req.body.discovery.discovery.name,
"objectType": req.body.discovery.discovery.objectType,
"description": req.body.discovery.discovery.description,
"location": req.body.discovery.discovery.location,
"discoveredOn": req.body.discovery.discovery.discoveredOn
});
//*********************************
//increase user discovery count
//**********************************
});
//******************************************************
//starts the server letting user know the PORT
app.listen(PORT, function(){
console.log("listening on port %d", PORT);
}); // end of app.listen
As #dustmouse said, I needed the ()...oops!
I am trying to make a portal for filling up a form for which an applicant needs to create an account before filling out the form. The only issue is how can I stop from spamming the applicant creating account with fake mail. Is it possible to verify email in sail. I have done this in express using node mailer.
var express = require('express');
var nodemailer= require('nodemailer');
var app = express();
var smtpTransport = nodemailer.createTransport("SMTP", {
service: "Gmail",
auth: {
user: "email",
pass: "pass"
}
});
var rand, mailOptions, host, link;
/*---SMTP OVER---*/
/*--Routing Started--*/
app.get('/', function(req , res) {
res.sendfile('index.html');
});
app.get('/send', function(req , res) {
rand=Math.floor((Math.random() * 100) + 54);
host= req.get(host);
link="http://"+req.get('host')+"/verify?id="+rand;
mailOptions={
to : req.query.to,
subject : "Please confirm your Email account",
html : "Hello,<br> Please Click on the link to verify your email.<br>Click here to verify"
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
});
app.get('/verify',function(req,res){
console.log(req.protocol+":/"+req.get('host'));
if((req.protocol+"://"+req.get('host'))==("http://"+host))
{
console.log("Domain is matched. Information is from Authentic email");
if(req.query.id==rand)
{
console.log("email is verified");
res.end("<h1>Email "+mailOptions.to+" is been Successfully verified");
}
else
{
console.log("email is not verified");
res.end("<h1>Bad Request</h1>");
}
}
else
{
res.end("<h1>Request is from unknown source");
}
});
/*--------------------Routing Over----------------------------*/
app.listen(9999,function(){
console.log("Express Started on Port 3000");
});
Any help will be appreciated Thanks
You should be able to use nodemailer in sails pretty much the same, just change the app.gets into corresponding controller actions.
MailController.js:
module.exports = {
sendVerificationMail: function(req, res) {
// your app.get('/send') code
},
verifyEmail: function(req, res) {
// your app.get('/verify') code
}
}
As a side note, your verifying logic kinda breaks when another user tries to register before the first one has completed his registration:
First user requests for email verification, rand = 34 for example
Second user requests for email verification, rand = 58
First user tries to verify his email with id=34, verification fails since 34 !== 58
I just need to have a user send private message to another user.
I have a service in angular with methods:
onSend:function(data) {
socket.emit('notification:save', {
message:'fromClient'
});
console.log("emittted")
},
onReceive:function(){
socket.on('notification:save',function(message){
console.log("recieved notif on mesage send")
})
console.log("recieved")
}
controller:
if(Auth.isLoggedIn()){
socket.onReceive();
}
$scope.sendMessage = function () {
socket.onSend($scope.message.newMessage);
$scope.message.newMessage = '';
};
It emits the event when I call $scope.sendMessage function but never is able to listen to the event i.e onReceive is never triggered.
How do I make this adapt to send to a particular client?
I need to listen and emit event both at front end. Just a notification so nothing that I need to store in db. Do I still have to include server side in this part of emit and on for events.
Here is a simple example of a private message server using socket.io. this uses nodejs and express on the server side, jquery on the client and socketio on both. the client.html is for demonstration only. in angular you would supply the username before connection to the socket.io server. in client.html you will need to enter it in the username field then click connect on both clients before sending messages. to test you can use 2 different browsers (ie. firefox for 1 client, chrome for another) make sure the user name is different on each client otherwise you will be sending messages to yourself.
server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var _ = require('lodash');
var clients = {};
app.get('/', function(req, res){
res.send('<h1>Message Server</h1>');
});
io.on('connection', function(socket){
// store the socket with the username if a reply event was emitted
socket.on('reply.username', function(username) {
console.log('Got Username reply', username);
clients[username] = socket;
});
// handle direct messages
socket.on('msg.private', function(obj) {
console.log('routing private message');
if (obj.to && clients[obj.to]) {
console.log('delivering to', obj.to);
clients[obj.to].emit('msg.private', obj.message);
}
});
// emit a request to the client to send its username back
socket.emit('send.username');
});
//start the server
http.listen(3000, function() {
console.log('Started server');
});
client.html
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>
<script>
var socket;
function connectIO() {
socket = io.connect('http://localhost:3000/');
socket.on('send.username', function() {
console.log('Server requested username');
socket.emit('reply.username', $('#username').val());
});
// recieve a message
socket.on('msg.private', function(msg) {
$('#chat').html(msg);
});
}
// send the pm
function sendPM() {
socket.emit('msg.private', {
to: $('#to').val(),
message: $('#msg').val()
});
$('#message').val('');
}
</script>
<form>
<textarea id="chat" rows="10" cols="10"></textarea><br>
Username: <input type="text" id="username"><br>
To: <input type="text" id="to"><br>
Message: <input type="text" id="msg"><br>
<span onclick="sendPM()">Send</span><br>
<span onclick="connectIO()">Connect</span>
</form>
</body>
</html>