Cross origin request block Node.js - javascript

i have a simple code that makes ajax interactions, it used to work perfectly about 1 week ago, but when i checked it today it says in the console : Blocking a Cross-Origin Request: The "Same Origin" policy does not allow the remote resource located at http://localhost:8080/api/user. Reason: CORS request failed.
I use firefox so i installed the plugin Cors everywhere, but no results yet.
My code :
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Hello World!</h1>
<div>
<h1>Sending User</h1>
<form id="userForm">
<label for="name">Name</label>
<input id="name" name="name"/>
<br/>
<label for="age">Age</label>
<input id="age" name="age"/>
<br/>
<input type="submit" value="Send"/>
</form>
</div>
<br/>
<br/>
<div>
<h2>Click the button below for getting User from server and showing it</h2>
<button id="getUserButton">Get User</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script>
$(document).ready(function () {
$('#userForm').submit(function (e) {
var user = {
name: $('input[name=name]').val(),
age: $('input[name=age]').val()
};
$.ajax({
type: 'POST',
url: 'http://localhost:8080/api/user',
data: user
})
.done(function (data) {
// clear form
$('input[name=name]').val('');
$('input[name=age]').val('')
alert(data);
});
e.preventDefault();
});
$('#getUserButton').click(function (e) {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/api/user'
})
.done(function (data) {
alert(JSON.stringify(data));
});
});
});
</script>
</body>
</html>
test.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var userStoredInMemory = {};
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/api/user', function (req, res) {
res.json(userStoredInMemory);
});
app.post('/api/user', function (req, res) {
userStoredInMemory = req.body;
res.send('User was already stored from express.');
});
app.listen(8080, function () {
console.log('server up and running at 8080 port');
});

Related

NodeJS - socket.on doesn't appear to be called

I am using the Node.JS POST method to submit a form to my server. It is transmitted to the server fine; no problems occur at this stage. However, when I use io.emit with socket.io to transfer the data back to the client, nothing seems to happen client-side. Nothing is printed to the console and I'm getting no errors there or in Command Prompt (where I'm running the server from).
index.html:
<form id="schoolCreateForm" action="http://localhost:3000/createSchool" method="POST">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit">Submit</button>
</form>
<script>
var socket = io();
socket.on('updateSchool', function(response) {
console.log(response);
document.getElementById("headerSchoolName").innerHTML = data.schoolName;
});
</script>
app.js:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var io = require('socket.io')(serv);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.post('/createSchool', function(req, res) {
response = {
school_name: req.body.schoolName,
school_private: req.body.schoolPrivate,
entry_password: req.body.entryPassword
};
console.log(response);
res.sendFile(__dirname + '/client/index.html');
io.emit('updateSchool', response);
});
serv.listen(3000);
console.log("Server started on localhost://3000");
Does anyone know what's going on?
<form action="http://localhost:3000/createSchool" method="POST">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit" id="schoolCreateForm">Submit</button>
After submitting your form data it will reload your page, it means socket connection will be ended. If you want to see a response with socket make ajax.post request without reloading the page.
<form id="schoolCreateForm">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit">Submit</button>
</form>
<script>
document.querySelector('#schoolCreateForm').addEventListener('click',
function(e) {
e.proventDefault() // this line will not all to reload page after
/// submitting the
//form data
### writh you ajax request functionality here
})
var socket = io();
socket.on('updateSchool', function(response) {
console.log(response);
document.getElementById("headerSchoolName").innerHTML = data.schoolName;
});

How can i store the text from a html input field in a node.js variable?

My node.js code looks like this:
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic("WebDir")).listen(80, function(){
console.log('Server running on port 80...');
});
I would like to use an API and use the data from the input field in node.js
How can i exactly do it. The Input field is just a normal input field in HTML
You can create a simple test setup for this using Node.js Express..
2 files: index.js, index.html
index.html
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
var sendInput = function() {
var inputField = $('#inputField').val();
console.log(inputField);
$.ajax({
type: 'POST',
url: 'http://localhost:3000/inputData',
crossDomain: true,
data: JSON.stringify({ inputField: inputField }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result, status){
document.getElementById("output").innerHTML = result.nodeVariable;
},
error: function (errorMessage) {
console.error('Error: ', errorMessage);
}
});
}
</script>
</head>
<body topmargin="40" leftmargin="40">
<div id="result">Loading..</div>
</br>
<button onClick="sendInput()">Send input to Node.js</button> : <input type="text" id="inputField" value="test value"><br>
<div>
<br/>Result: <p id="output"></p>
<div>
</body>
</html>
Server side, this is the node.js script.
index.js
const bodyParser = require('body-parser');
const express = require('express');
const port = (process.env.PORT || 3000);
const app = express();
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.post('/inputData', (req, res, next) => {
console.log('/inputData post: ', JSON.stringify(req.body));
// Read the variable..
var inputField = req.body.inputField;
console.log('Input field: ', inputField);
res.status(201).send(JSON.stringify({status: 'OK', nodeVariable: inputField + " - updated by node."}))
});
app.listen(port);
console.log('Express listening on port ' + port);
Go to http://localhost:3000 on your browser to test.

Can not able to store data on mongoDB with Angular,js and Node,js

I am learning the MEAN stack. As I was trying to execute the basic program where I am storing HTML form data mongoDB by using Angular.js and node.js. But I am getting error and I am not able solve it.
console output:
clicked submit
index.html:1 XMLHttpRequest cannot load http://localhost:8080/blah.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
angular.min.js:123 Possibly unhandled rejection:
{"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:8080/blah","data":{},"headers":{"Accept":"application/json,
text/plain,
/","Content-Type":"application/json;charset=utf-8"}},"statusText":""}
I am posting code of html file, angular js file and node.js file
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/app.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<form>
Author:
<input type="text" ng-model="author">
<br>
<br> Title:
<input type="text" ng-model="title">
<br>
<br> Body:
<input type="author" ng-model="body">
<br>
<br>
<input type="submit" value="Submit" ng-click="submit()">
</form>
</div>
</body>
</html>
app.js
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
$scope.data = {};
$scope.submit= function(){
console.log('clicked submit');
$http({
url: 'http://localhost:8080/blah',
method: 'POST',
data: $scope.data
}).then(function (httpResponse) {
console.log('response:', httpResponse);
})
}
});
server.js
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
//const url = 'mongodb://localhost:27017/conFusion';
var port = 8080;
var app = express();
app.use(bodyParser.json({limit: '50mb'}));
app.use(express.static('public'));
app.post('/blah', function(req, res, next){
var cope = req.body.params;
db.collection('book').insert(cope, (err, result) => {
if (err)
{
res.send({ 'error': 'An error has occurred' });
}
else
{
res.send(result.ops[0]);
}
});
});
app.listen(port, () => {
console.log('We are live on ' + port);
});
Render index.html from server add this code in your server.js file
app.get('/', function(req, res) {
res.sendFile('/absolute/path/to/index.html');
});
and add slash to your scripts paths in index.html
<script src="/Scripts/angular.min.js"></script>
<script src="/Scripts/app.js"></script>
no visit http://localhost:8080 and you will see your file send post request from here
<form ng-submit="submit($event)">
Author:
<input type="text" ng-model="author">
<br>
<br> Title:
<input type="text" ng-model="title">
<br>
<br> Body:
<input type="author" ng-model="body">
<br>
<br>
<input type="submit" value="Submit">
</form>
app.js
$scope.submit = function(e) {
e.preventDefault();
$http({
url: '/blah',
method: 'POST',
data: $scope.data
}).then(function(httpResponse) {
console.log('response:', httpResponse);
})
});

Unable to send form data to server side (nodejs) using ajax

I am trying to send form data via ajax to a nodejs server. Previously asked on this post.
Here's what my code looks like:
<div id="inputid" style="width: 400px; height:400px">
<p> Please enter a value between -90 and 90 for lat, and -180 and 180 before hitting
submit.</p>
<form id="sendCoordinates" action="http://localhost:8080/geodata" method="post">
MinLat: <input type="text" name="MinLat" value="15" id="minlat"><br>
MaxLat: <input type="text" name="MaxLat" value="25" id="maxlat"><br>
MinLong: <input type="text" name="MinLong" value="-10" id="minlong"><br>
MinLong: <input type="text" name="MaxLong" value="120" id="maxlong"><br>
<input type="submit" value="submit" id="s1">
</form>
<script>
$(document).ready(function() {
console.log("hi hi");
$("#sendCoordinates")
.on('submit', function(e) {
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray();
$.each(params, function(i, val) {
// console.log(val);
formData.append(val.name, val.value);
});
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(result) {
console.log("hi helo");
}
});
});
});
</script>
</div>
My server side code looks like this :
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
// for debugging purposes, just logging the request to check
// if request received
app.post("/geodata", function(req, res) {
console.log("hey");
console.log(req.body);
res.send("hi back!");
});
I am trying this out but I am unable to send the form successfully, and upon hitting submit, I get "hey" and an empty {} as logged output. I am not able to log the formData on the client side, regardless.
Can someone point out what I might be doing wrong?
You didn't assign a form to formData() that's why you're not sending any data to the server.
var myForm = $('#sendCoordinates')[0];
var formData = new FormData(myForm);

Send AJAX data to node express

I am trying to send data with AJAX to node express, but as I handled it without express module (with if (req.method="POST"){function on data...})
as I can catch it with express.
NODE code to catch data:() for now nothing happens even in console.log)
app.get('/getdata',function(req, res){
res.send('Something');
});
app.post('/getdata', function (req, res){
console.log(req.body.objectData);
res.contentType('json');
res.send({ some: JSON.stringify({response:'json'}) });
});
app.listen(process.env.PORT || 5073);
A HTML page with AJAX call:
$(document).ready(function () {
$('#Send').on('click', function () {
var toSend = $('#Sth').val();
alert(toSend);
$.ajax({
type: "POST",
dataType: "json",
data: { objectData: toSend },
contentType: "application/json",
cache: false,
url: 'http://127.0.0.1:5073/'
});
});
});
<body>
<input id="Sth" type="text" name="Content" />
<div id="select_div">Test</div>
<div id="test"> Content to be copied</div>
<input id="Send" type="submit" />
</body>
Well, I do not know what to do, please help.
Care to give this a shot?
app.post('/endpoint', function(req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body));
res.send(req.body);
});
https://gist.github.com/diorahman/1520485

Categories