I'm calling an express endpoint from after form submission in Jquery. So when the form submits, it calls signUpUser(value) which then initiates an ajax request to the express server.
The call to /signup is resulting in a 404, I thought I was setting up the endpoint properly.
Any reason it is giving a 404? I've tried GET/POST and a few other iterations.
$(document).ready(function(){
$('#signupForm').submit(function() {
console.log("here");
console.log("yup");
var value=$("#email").val();
signUpUser(value);
});
var signUpUser = function (value){
console.log("yaaa");
$.ajax({
type:"GET",
url:"/signup"
})
.done(function(){
window.location='/confirmation.html';
})
.fail(function(){
alert('An error occurred while trying to sign up. Please try again.')
});
};
});
var express = require('express');
var app = express();
var cors = require('cors');
var path = require('path');
var bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
var router = express.Router();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/thesis.html', function(req, res) {
res.sendFile(path.join(__dirname + '/thesis.html'));
});
app.get('/confirmation.html', function(req, res) {
res.sendFile(path.join(__dirname + '/confirmation.html'));
});
app.get('/about.html', function(req, res) {
res.sendFile(path.join(__dirname + '/about.html'));
});
app.post('/signup', function (req, res) {
$.ajax({
type:"POST",
url:"https://us11.api.mailchimp.com/3.0/lists/8085fb931b/members",
user: 'anystring:XX',
header: 'content-type: application/x-www-form-urlencoded',
data: { "email_address": "ttttt#ssssssss.com",
"status": "subscribed"
}
})
.done(function(){
window.location='/confirmation.html';
res.send(200);
})
.fail(function(){
alert('An error occurred while trying to sign up. Please try again.')
});
});
<form id="signupForm" ng-controller="formController">
<fieldset>
<input type="test" id="email" name="field1" id="field1" ng-model="email">
<input type="submit" value="Create Profile">
</fieldset>
</form>
The end point you're trying to hit, /signup, is a declared as a POST end point. The type attribute in your ajax request is GET. You're getting a 404 because you're trying to make a request to a GET end point that doesn't exist.
Related
I defined a route in my Express app that supposed to execute a line of code then return a JSON file, but what happens is that the file is returned, but the line of code isn't executed.
This is the server code:
var express = require('express');
var body_parser = require("body-parser");
var path = require('path');
server = express();
server.use(body_parser.json());
server.use(body_parser.urlencoded({ extended: true }));
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
Inside index.html there is only a script tag defined like:
<body>
<script>
$(document).ready(function(){
$.getJSON("/request.json", function(data) {
console.log(data)
});
})
</script>
</body>
I can see the content of request.json file in chrome console, but the expected message "File "request.json" requested" isn't displayed on server's terminal.
Why the route isn't being executed?
The express.static is called before the /request.json route and already returns the file.
Use this:
const express = require('express');
const bodyParser = require("body-parser");
const path = require('path');
server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
You can write custom static middleware. Can write logic to not to serve file[exclude].
Note: Note recommend from me, better change route name of /response.json
var express = require("express");
var path = require("path");
var app = express();
var statics = express.static(path.join(__dirname, "/"));
function customServe(secure) {
return function (req, res, next) {
console.log(req.path);
if (req.path != "/response.json") return statics(req, res, next);
return next();
};
}
app.use(customServe());
app.get("/response.json", (req, res) => {
console.log("something...");
res.send({ json: "json" });
});
app.listen(8080, () => console.log("working on 8080"));
I'm learing ExpressJS, i want to do the login part , but i gave me this
Cannot POST /login
im using the post method why it gave me this error
here a detailed post , thank you in advance for helping me
html part
<form method="POST">
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="name" >
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password">
<button type="submit">Login</button>
</div>
</form>
The route.js
router.post('/login'),(req,res)=>{
var username= req.body.name;
var password = req.body.password;
con.query('SELECT * FROM authentication WHERE username = ?',username, function (error, results, fields) {
if (error) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
// console.log('The solution is: ', results);
if(results.length >0){
if(results[0].password == password){
res.send({
"code":200,
"success":"login sucessfull"
});
}
else{
res.send({
"code":204,
"success":"username and password does not match"
});
}
}
else{
res.send({
"code":204,
"success":"username does not exits"
});
}
}
});
}
module.exports = router
index.js
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
when trying to post this form i'm getting:
Cannot POST /login
what am i missing here?
You should handle current page, not '/login' page in route.js :
router.post('/', //...
Instead of writing
router.post('/login', //...
Because you sent the form data to the current page not to the '/login' page
Why current page ?
Because, you didn't define action attribute in your form
You need to define form action
<form action="/login" method="post">
But I recommend you to use js for sending requests
fetch('/login', {
method: 'POST',
body: JSON.stringify(yourFormData),
// ...another Opts if it needs
})
Also it can be problem with your server code because I don't see defining router in indexRouter file, you should add it:
const express = require('express');
const router = express.Router();
// then your code:
router.post('/login', loginController);
But you can add this line for check post requests:
app.post('/login', (req, res) => {
res.status(201).json(req.body); // or console.log
});
I am currently trying to build simple online forum where people can post comments; however, I am not sure how I write is correct way to do. Is Ajax automatically called after the form is submitted by choosing type="POST"?
I am also not sure if I am writing correct programs in routes file.
Here is my code.
<!DOCTYPE>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// $(function(){
// $("#target").submit(function(event){
// event.preventDefault();
// $.post("/users", function(data){
// $( "#result" ).html( JSON.stringify(data) );
// });
// });
// });
//Not sure which way I should use ↑↓
$.ajax({
type: "GET",
url: 'http://localhost3000/users',
data: data,
dataType: 'json'
})
.done(function(data){
console.log("GET Succeeded");
$('#result').html(JSON.stringify); //What should I put after JSON.stringify?
});
$(function(){
$("#target").submit(function(event){
$.ajax({
type: "POST",
url: 'http://localhost3000/users',
data: data,
dataType: 'json'
})
.done(function(data){
console.log("POST Succeeded");
$('#result').html(JSON.stringify); //What should I put after JSON.stringify?
});
});
});
</script>
</head>
<body>
<div id="result"></div>
<form action="/users" method="post" id="target">
Username:<input type="text" name="username">
<input type="submit" value="Post">
</form>
</body>
</html>
Here is my routes file
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Users = require('../models/users');
var userRouter = express.Router();
userRouter.use(bodyParser.json());
userRouter.route('/')
.get('/users', function (req, res, next) {
Users.find({}).then(function(user){
res.json(user)
}).catch(next);
})
.post(function(req, res, next){
// res.send("Confirmed");
Users.create(req.body).then(function(user){
res.send(user);
}).catch(next);
res.json(newUser);
});
module.exports = userRouter;
Here is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var url = 'my database';
mongoose.connect(url);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log("Connected correctly to server");
});
var routes = require('./router/index');
var userRouter = require('./router/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', userRouter);
//Error handler for user
app.use(function(err, req, res, next){
res.status(422).send({error: err.message});
});
//catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
if (app.get('env') === 'development'){
app.use(function(err, req, res, next){
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
});
app.use(function(err, req, res, next){
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Thank you:)
your ajax post is not automatically called upon form submission. However, this being said, the browser does send a post to the specified endpoint in your form tag.
If you need to automatically display the comments as the posts are made, then you could use the commented block of code in your script.
Another approach would be to do the following....
$(function(){
$("#target").submit(function(event){
// add code here to append the form data to the DOM
// dont call event.preventDefault()
// doing so will take advantage of the browser's
// post functionality while giving you a chance
// to handle the form data locally prior to the post
});
});
i suggest the postman chrome plugin,it is a restful api client,you first call the api through it,and then if the api performs perfect,you can write the ajax post else.
I am trying to log in a user from a web site. I am using parse-server hosted at Microsoft Azure. I keep getting the following error, just trying to access the home page:
Error handling request: ParseError { code: 209, message: 'invalid session token' } code=209, message=invalid session token
And the browser throws a "...redirected you too many times." error. I'm not sure what I'm doing wrong, I've tried researching and piecing this together from here: https://github.com/ParsePlatform/parse-server/issues/497 with no luck.
index.js
var express...
etc...
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({extended:false});
//Server configuration
...
//Express configuration
var app = express();
app.use(cookieParser()); // read cookies (needed for auth)
// get information from html forms
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use('/public', express.static(__dirname + '/public'));
app.use('/parse', new ParseServer(config.server));
app.use('/parse-dashboard', ParseDashboard(config.dashboard, true));
app.use(cookieSession({
name: "COOKIE_NAME",
secret: "COOKIE_SECRET",
maxAge: 15724800000
}));
app.use(function (req, res, next) {
Parse.Cloud.httpRequest({
url: 'https://localhost:1337/parse/users/me',
headers: {
'X-Parse-Application-Id': process.env.APP_ID,
'X-Parse-REST-API-Key': process.env.API_KEY,
'X-Parse-Session-Token': req.session.token
}
}).then(function (userData) {
req.user = Parse.Object.fromJSON(userData.data);
next();
}).then(null, function () {
return res.redirect('/login');
});
});
app.use(flash()); // use connect-flash for flash messages stored in session
//routes
require('./routes/routes.js')(app);
app.listen(process.env.PORT || url.parse(config.server.serverURL).port, function () {
console.log(`Parse Server running at ${config.server.serverURL}`);
});
routes.js
// app/routes.js
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({extended:false});
module.exports = function(app) {
// HOME PAGE ========
app.get('/', function(req, res) {
res.render('index.ejs', { title: 'Audiomesh' }); // load the index.ejs file
});
// LOGIN ===============================
// show the login form
app.get('/login', function(req, res) {
res.render('login.ejs', { message: req.flash('loginMessage') });
});
app.post('/login', function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
req.session.user = user;
req.session.token = user.getSessionToken();
res.redirect('/dashboard');
}, function(error) {
req.session = null;
res.render('login', { flash: error.message });
});
});
// DASHBOARD =====================
app.get('/dashboard', function(req, res) {
res.render('dashboard.ejs', {
user : req.user // get the user out of session and pass to template
});
});
// LOGOUT ==============================
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
};
login.ejs
<body>
<p><%= message %></p>
<form name="loginForm" action="/login" method="post">
<label>Email</label>
<input type="email" name="email"></input>
<label>Password</label>
<input name="password" type="password"></input>
<input class="button" type="submit" value="Log In">
</form>
<p>Coming soon azure</p>
<p>Back to home page</p>
</body>
The goal of my web site is for the home page to be an advertising/landing page for the mobile app. So if you're logged in, there's no evidence here. Once you click "Login" then it would check if the user is logged in and either load their dashboard (if true), or the login page (if false).
The problem right now is I can't even load the home page. I get too many redirects.
I need a complete basic example in Node.js of calling a server-side function from (client side) html button onclick event, just like in ASP.NET and C#.
I am new to Node.js and using the Express framework.
Any help?
IMPROVED QUESTION:
//server side :
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('views',__dirname + '/views');
app.set('port', process.env.PORT || 3000);
app.engine('html', require('ejs').renderFile);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'html');
app.use(app.router);
app.get("/",function(req,res)
{
res.render('home.html');
});
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
//Client Side
<input type="button" onclick="" /> <--just want to call the serverside function from here-->
Here's an example using Express and a HTML form.
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.use(express.bodyParser());
app.post('/', function(req, res) {
console.log(req.body);
res.send(200);
});
server.listen(process.env.PORT, process.env.IP);
The code above will start an instance of Express, which is a web application framework for Node. The bodyParser() module is used for parsing the request body, so you can read post data. It will then listen for POST requests on the route /.
<form method="post" action="/">
<input type="test" name="field1">
<input type="test" name="field2">
<input type="submit">
</form>
And if you submit that form, in req.body for the route /, you will get the result:
{ field1: 'form contents', field2: 'second field contents' }
To run a function, just put it inside the POST handler like this:
var foo = function() {
// do something
};
app.post('/', function(req, res) {
console.log(req.body);
res.send(200);
// sending a response does not pause the function
foo();
});
If you don't want to use Express then you can use the native HTTP module, but you'd have to parse the HTTP request body yourself.
var http = require('http');
http.createServer(function(request, response) {
if (request.method === 'POST') {
var data = '';
request.on('data', function(chunk) {
data += chunk;
});
request.on('end', function() {
// parse the data
foo();
});
}
}).listen(80);