ExpressJS does not seem to work with ajax calls - javascript

I'm trying to figure out Node.js to use as an api to do GET, POST, etc. I've been stuck trying to figure out why this post is not working.
My ajax call:
$.ajax({
method: "POST",
contentType: 'application/json',
dataType: 'json',
url: "localhost:8000/login",
data: JSON.stringify({user:"john", pass:"123"}),
error: function () {
alert('error');
},
success: function (data) {
alert('success');
}
});
In my express:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/login', function (req, res) {
var user = req.body.user;
var password = req.body.pass;
if(user == 'john' && password == '123') {
res.status(200);
} else {
res.status(401);
}
});
app.listen(8000, function () {
console.log('Example app listening on port 8000!');
});
Any help is greatly appreciated.

you should return some response from your express code, also response should be ended especially in case of just sending only the status code like res.status(401);
app.post('/login', function (req, res) {
var user = req.body.user;
var password = req.body.pass;
if(user == 'john' && password == '123') {
res.status(200).json({t:1});
} else {
res.status(401);
}
res.end();
});

This work for me:
$.ajax({
type: "POST",
contentType: 'application/json',
dataType: 'json',
url: "/login",
data: JSON.stringify({user:"john", pass:"123"}),
error: function (err) {
console.log(err);
alert('error');
},
success: function (data) {
alert('success');
}
});
app.post('/login', function (req, res, next) {
var user = req.body.user;
var password = req.body.pass;
if(user == 'john' && password == '123') {
res.status(200).json({s: 1});
} else {
res.status(401).json({e: 2});
}
});

var json = JSON.stringify({user:"john", pass:"123"});
$.ajax({
dataType: 'json',
type: "POST",
url: "/login",
data: json
}).done(function(data){
console.log("works fine");
});
Should work for an Ajax post function, sending the data to the node server.
The url needs to match the url of the app.post in the node server file, you don't need localhost in front of it.
ContentType is also not necessary and I made the json object outside of the Ajax call instead of setting it inside the Ajax call.
var express = require('express');
var parser = require('body-parser');
var app = express();
var port = 8000;
app.use(parser.urlencoded({extended: false}));
app.use(parser.json());
app.use(express.static('public'));
app.post('/login', function (req, res) {
var user = req.body.user;
var password = req.body.pass;
if(user == "john" && password == "123") {
res.status(200);
} else {
res.status(401);
}
});
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port);
});
And that should work for the node server itself.
I set the server running, so you can always keep track of what port it's listening on, so you don't need to bother scrolling down to change the port, just change the port at the top of your file.
Further the /login was looking fine to me.
Also, I edited the app.use statements and added an extra one.

I think you have to parse request to JSON.
your code is:-
$.ajax({
method: "POST",
contentType: 'application/json',
dataType: 'json',
url: "localhost:8000/login",
//here you used JSON.stringify and on server side you have to parse it to use 'user' and 'pass' as a key of json
data: JSON.stringify({user:"john", pass:"123"}),
error: function () {
alert('error');
},
success: function (data) {
alert('success');
}
});
on the server side
<br>
app.post('/login', function (req, res) {
//parse data to JSON for further use
var dataObj = JSON.parse(req.body.data);
if(dataObj.user == 'john' && dataObj.password == '123') {
res.status(200);
} else {
res.status(401);
}
});

Related

How to POST JSON data to server using AJAX jQuery

Keep getting error when trying to post 'order' JSON data to JSON file on Node.js server
GET request works fine but 'Error' function executes instead of the 'success' function when trying to do a POST request. Am I missing anything? Do I need to use php?
The dev tools console shows the following error message:
POST http://.../orders.json 405 (Method Not Allowed) jquery.js:10109
$("#add-order").on("click", function()
{
var order =
{
name: $name.val(),
food: $food.val()
};
$.ajax(
{
type: "POST",
url: "orders.json",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(order),
processData: false,
success: function(newOrder)
{
alert("success");
$orders.append("<li>Name: " + newOrder.name +", food: " + newOrder.food + "</li>");
},
error: function()
{
alert("Error posting order");
}
});
});
Node js server
const http = require("http");
const fs = require("fs");
const port = 3000;
const server = http.createServer(function(request, response)
{
response.writeHead(200, { "Conent-Type": "text/json" })
fs.readFile("orders.json", function(error, data)
{
if (error)
{
response.writeHead(404);
response.write("Error: File Not Found");
}
else response.write(data);
response.end();
})
});
server.listen(port, function(error)
{
if (error) console.log("Something went wrong. Error: ", error);
else console.log("server is listening to port " + port);
})
var http = require('http');
var requestListener = function(req, res) {
console.log("" + req.method)
if (req.method === "POST") {
let data = '';
req.on('data', chunk => {
data += chunk;
})
req.on('end', () => {
console.log(data)
res.end("received");
})
}
res.writeHead(200);
res.end('Hello, World!' + req.method);
}
var server = http.createServer(requestListener);
server.listen(3000, function() {
console.log("Listening on port 3000")
});
//curl -d '{"name":"1","age":"2"}' -H 'Content-Type: application/json' localhost:3000
//Output
/*
Listening on port 3000
POST
undefined
{"name":"1","age":"2"}
*/
Or you can explore express or any other middle ware for easy parsing and handling.

Express js does not return data after success to Ajax call

I am trying to store the data from client end javascript to server end express js after storing returning some data. I can receive the data at express API userdetail function but unable to return to ajax. Please can I get help?
$.ajax({
url: "http://localhost:8080/api/save_user/",
type: "POST",
crossDomain: true,
data: { name: 'Justin', number: '662***' },
dataType: "json",
contentType: "application/json",
success: function (response) {
var resp = JSON.parse(response)
},
error: function (xhr, status) {
alert("error");
}
});
Express Js server side
const express = require('express');
const path = require('path')
const os = require('os');
const app = express();
var bodyParser = require('body-parser')
app.use(bodyParser.json())
app.post('/api/save_user', (req, res) => {
Usermodel.saveData(req.body.name,req.body.number)
.then(function (userdetail) {
res.send({ success: true, data: userdetail });
})
.catch(next);
})

$.ajax is not a function when being called

for some reason when I run npm start and I hit the browser, I am getting this stack trace with this error.
TypeError: $.ajax is not a function
at getLocationFromIp (G:\Github\Expressjs\nodetest1\routes\index.js:13:7)
at G:\Github\Expressjs\nodetest1\routes\index.js:24:14
Would someone be able to tell me why? Here is my code. Thanks!
var express = require('express');
var router = express.Router();
var externalip = require('external-ip');
var $ = require('jquery');
getLocationFromIp = function() {
$.ajax({
url:"freegeoip.net/json/",
type: "GET",
data: null,
dataType: "json",
success: function(){console.log("success!")}
});
}
router.get('/', function(req, res) {
var ip = getLocationFromIp();
res.render('index', { 'ip' : "hi"});
});
See the documentation:
For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as jsdom. This can be useful for testing purposes.
var externalip = require('external-ip');
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
function getLocationFromIp() {
$.ajax({
url: "freegeoip.net/json/",
type: "GET",
data: null,
dataType: "json",
success: function() {
console.log("success!")
},
error: function() {
console.log("error", arguments[2])
}
});
}
var ip = getLocationFromIp();
console.log(ip);
});
You'd probably be better off using an HTTP library designed to work with Node from the outset, such such as request.
If you are using jquery to just make a http request, you can probably use the http or request node module to do that instead.
var express = require('express');
var router = express.Router();
var externalip = require('external-ip');
var http = require('http');
getLocationFromIp = function(done) {
var options = {
host: "freegeoip.net",
port: 80,
path: "/json"
};
var request = http.get(options, function(response) {
var result = "";
var responseCode = response.statusCode;
response.on('data', function(data) {
result += data;
});
response.on('end', function() {
if(responseCode >= 400)
return done(result, null);
else
return done(false, JSON.parse(result));
});
});
request.on("error", function(error){
return done("Error handling error", null);
});
request.end();
}
router.get('/', function(req, res) {
var ip = getLocationFromIp(function(error, ip){
res.render('index', { 'ip' : "hi"});
});
});

node js error on response methods between server and client

Hey im currently working on my first real webpage using node.js
Im using Express, ejs for layout and redis as database. Im trying to send an ajax call from my index page through my client to my server, use the ajax-call there and pass the final json back to my client where i try to render it on the next ejs page.
Ajax:
$(function(){
$(".search").click(function() {
$.ajax({
method: "POST",
url: "/search",
cache: false,
data: {ort: "hierundda", activity: "Wandern", datum: "01.09.2015"},
dataType: "json",
success: function(data){
alert('Success!')
}
, error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err)
}
});
});
});
My server route:
rest.post("/search", jsonParser, function(req, res){
/*some database action with redis */
res.json(dataJson);
});
});
My client route:
app.post('/search', jsonParser, function(req,res){
var test = JSON.stringify(req.body);
fs.readFile('./filterergebnis.ejs', {encoding: 'utf-8'}, function(err, filestring){
if(err){
throw err;
}
else{
var options = {
host: 'localhost',
port: 3000,
path: '/search',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': test.length
}
}
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
var userdata = JSON.parse(chunk);
console.log(userdata);
var html = ejs.render(filestring, userdata);
//here does the error appear...
res.setHeader('content-type', 'text/html');
res.writeHead(200);
res.write(html);
res.end();
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(test);
req.end();
}
});
});
This is what the error looks like:
http://www.pic-upload.de/view-28225954/stack.png.html
index.ejs is running on default
You're using conflicting res variable names. Check the variable names of the callbacks from app.post() and http.request().
If you change to response instead, it might work, if there is no other problems:
var req = http.request(options, function(response) {
response.on('data', function (chunk) {
...

How to send a POST request from node.js Express?

Could someone show me the simplest way to send a post request from node.js Express, including how to pass and retrieve some data? I am expecting something similar to cURL in PHP.
var request = require('request');
function updateClient(postData){
var clientServerOptions = {
uri: 'http://'+clientHost+''+clientContext,
body: JSON.stringify(postData),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
request(clientServerOptions, function (error, response) {
console.log(error,response.body);
return;
});
}
For this to work, your server must be something like:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
var port = 9000;
app.post('/sample/put/data', function(req, res) {
console.log('receiving data ...');
console.log('body is ',req.body);
res.send(req.body);
});
// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);
As described here for a post request :
var http = require('http');
var options = {
host: 'www.host.com',
path: '/',
port: '80',
method: 'POST'
};
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("data");
req.end();
you can try like this:
var request = require('request');
request.post({ headers: {'content-type' : 'application/json'}
, url: <your URL>, body: <req_body in json> }
, function(error, response, body){
console.log(body);
});
in your server side the code looks like:
var request = require('request');
app.post('/add', function(req, res){
console.log(req.body);
request.post(
{
url:'http://localhost:6001/add',
json: {
unit_name:req.body.unit_name,
unit_price:req.body.unit_price
},
headers: {
'Content-Type': 'application/json'
}
},
function(error, response, body){
// console.log(error);
// console.log(response);
console.log(body);
res.send(body);
});
// res.send("body");
});
in receiving end server code looks like:
app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});
Schema is just two properties unit_name and unit_price.
I use superagent, which is simliar to jQuery.
Here is the docs
And the demo like:
var sa = require('superagent');
sa.post('url')
.send({key: value})
.end(function(err, res) {
//TODO
});
Try this. It works for me.
const express = require("express");
const app = express();
app.use(express.json());
const PORT = 3000;
const jobTypes = [
{ id: 1, type: "Interior" },
{ id: 2, type: "Etterior" },
{ id: 3, type: "Roof" },
{ id: 4, type: "Renovations" },
{ id: 5, type: "Roof" },
];
app.post("/api/jobtypes", (req, res) => {
const jobtype = { id: jobTypes.length + 1, type: req.body.type };
jobTypes.push(jobtype);
res.send(jobtype);
});
app.listen(PORT, console.log(`Listening on port ${PORT}....`));

Categories