AJAX and Node JS/Express post not sending or receiving data - javascript

I am new to Node and I am trying to use app.post, everything works fine including the console log whenever the action is executed but it does not receive the data sent by the AJAX from main.js.
Here is a snipper of main.js which sends it:
$.ajax({
type: 'POST',
data: '{"title":'+ this.messageInput.value +'}',
url: 'http://localhost:3000/send'
});
Here is my config.js which should be receiving the data:
app.post('/send', function(req, res) {
console.log(req.body);
console.log('Send button clicked');
});
I am using bodyParser with express. So that is why I am using req.body. When I console log req.body I get undefined. When I console log req, I get a list of data but not what I sent.
I hope someone can help!

It's good that you are using body-parser, but have you defined a JSON parser in your app?
You didn't paste all of your code so add this if you don't already have it:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser --> This is probably what you are missing
var jsonParser = bodyParser.json()
// POST /api/users gets JSON bodies --> Note how we use a jsonParser in our app.post call
app.post('/send', jsonParser, function (req, res) {
console.log(req.body);
console.log('Send button clicked');
})
Also, instead of constructing your data manually, just create an object and send it (remember JSON is short for - Java Script Object Notation)
var myData = {};
myData.title = this.MessageInput.value;
Then in your Ajax code, just use myData:
$.ajax({
type: 'POST',
data: myData,
url: 'http://localhost:3000/send'
});
Note: most of this example is taken straight from the body-parser Github Page, it has plenty of well documented examples so if you're not sure how to use the module, check it out

Related

node server cannot find the data in the body

i am sending a post request from fetch but the nodejs server is not able to access the body from the post request. I tried req.body but it just returns empty brackets.
const express = require('express');
const bodyParser=require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json());
app.use(express.json());
app.get("/user",function(req,res){
res.send("just Checking");
});
app.post("/user", (req, res) => {
console.log(req.body);
res.send("got the data");
});
app.listen(3000,function(res){
console.log("server is workig a t local host 3000");
});
This is the browser side code
const checking = { name:"badmintion" }
function yo (){
fetch("/user",{
method : "POST",
Headers : {
'Content-Type':'application/json'
},
body: JSON.stringify(checking)
})
}
yo();
In the browser i can see that the data is being sent but i am unable to recieve the in the nodejs server it just shows empty brackets.
Edit: I was able to recreate the server code locally on my machine. I didn't find any issues. I used Postman to send the JSON to the /user route. The issue you might be having is in the front end.
Headers should be lowercase. You have capitalized it:
...
fetch("/user",{
method : "POST",
headers : {
...
}
...
Make sure you're sending data in a JSON format so that express can parse it into object:
To avoid any conflict for (parse json) better that remove body parser completely and try again.
For request, according to stanley, headers set as lowercase. Its will be work.
This tutorial maybe help u:
https://www.geeksforgeeks.org/express-js-express-json-function/amp/

Handling form input in nodejs

I would like user to submit a URL as form input (e.g: "http://api.open-notify.org/astros.json") and read the content from the submitted URL.
I'm not sure if my current approach is correct. What should i put in the URL field below?
var options = {
url: '....',
method: 'GET',
headers: {'Content-Type' : 'application/x-www-form-urlencoded' }
}
You could do something like this (I guess this is what you want):
I suggest using request-promise package
const rp = require('request-promise');
// post router
app.post('/readUrl', async (req, res) => {
const uri = req.body.url // http://api.open-notify.org/astros.json
const options = {
uri,
headers: {
// maybe set some headers to accept other formats of response
},
// Automatically parses the JSON string in the response
json: true
};
const data = await rp(options);
// data is json
res.json(data);
})
It seems like you already have the Express logic loaded. IMO, if you have express already working, create a post route that the user can hit:
app.post("/form",(req,res)=>{
//See the request body here.
console.log(req.body)
);
You would then make your AJAX call with the URL you have above. It is worth noting that you will need a body parser on your server.js file.
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
The plugin allows easier parsing on the server side from the client.

Unable to make a GET request with AJAX under Node.js when using NGINX

Despite I have learned and implemented AJAX request with Node on my local server. I am finding that the requests that I created on my local server, just does not work at cloud server.
When I use AJAX to request data to the server (Node), the request does not get to the server because of the URL (or I think so).
Node Code:
app.get("/",function(req,res){
app.use(express.static(__dirname + '/'));
app.get("/mypath/",function(req,res){
console.log("please tell me that you arrive here"); //This actually never happens
//some functions using the data in "req" and putting there in var "data"
res.send(data);
});
});
Javascript Code:
$.ajax({
url: 'http://localhost:3000/mypath/',
type: 'GET',
data: {//some data to use on the server},
dataType: "json",
complete: function(data){
//some stuff with the transformed data
},
});
The code above works in the local server (my pc). But not in the cloud one, I had some problems trying to the server static files with NGINX and Express, but I was able to figure it out.
Do you think that given the way I am serving the static files and that I am working in the cloud server, I should use AJAX request in a different way when we are trying to communicate through an URL?
Console Log:
Console Log after using Marcos solution
EDIT: Code from jQuery AJAX and Node Request
Node Set-Up:
var express = require('express');
var app = express();
var request = require("request");
var db = require('mysql');
const path = require('path');
var http = require("http").Server(app);
var io = require("/usr/local/lib/node_modules/socket.io").listen(http);
http.listen(3000, 'localhost'); //At the end of everything between here and the code.
GET Node Code:
app.use(express.static(__dirname + '/'));
app.get('/reqData',function(req,res){
//I never arrive here
console.log("print that I am here");
transform(req.query.selection1,req.query.selection2,function(){
res.json(data); //data is transformed globally
});
});
Ajax:
function requestData(){
$.ajax({
url: 'http://localhost:3000/reqData',
type: 'GET',
data: {//Some stuff to send},
dataType: "json",
complete: function(data){
do(data);
},
error: function(e){
console.log(e);
}
});
}
New Console Log:
Chrome Console Error
The main issue you have, is how you're defining your routes, you will be unable to reach /mypath/ until you perform a request first to /.
You should not define your routes that way, each route should be defined individually, and not in a nested way.
app.get('*', (req, res, next) => {
// Set your cookies here, or whatever you want
// This will happen before serving static files
next(); // Don't forget next.
});
app.use(express.static(__dirname + '/'));
app.get('/mypath/', (req,res) => {
console.log("please tell me that you arrive here"); //This actually never happens
//some functions using the data in "req" and putting there in var "data"
res.send(data); // make sure it is defined.
});
And your route app.get('/') conflicts with express.static(__dirname + '/'), so you should just remove it if you're only serving an index.html file, which seems to be your case.
Then in your $.ajax you should add the protocol to the URL.
$.ajax({
url: 'http://yourdomain.com/mypath/',
// url: 'http://localhost:3000/mypath/',
/* ... */
});
Now, supposing you have everything else setup correctly, you will be able to access /mypath

I use routes in my Node.JS app and when I try to open one of the routes from the browser I get an error

That's my app. When I try to open ip/delete I get an error
Cannot GET /delete
I'm following this tutorial, https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function(req, res) {
console.log("Got a GET request");
res.send('GBArena Labs');
})
app.post('/', function(req, res) {
console.log("Got a POST request");
})
app.delete('/delete', function(req, res) {
res.send('Delete');
console.log("Got a DELTE request");
})
app.listen(8081);
You can't navigate to a DELETE. You have to send a DELETE request. In example :
<a href="/delete">My delete link<a/> will be sent as a GET request and not a DELETE.
In order to hit your delete endpoint, you would have to use a ajax library like jquery $.ajax and using
$.ajax({
url: '/delete',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
from the client side.
There are many ways, but i would suggest you looking into : HTTP verbs
You may need to call the route without the /delete and use the HTTP verb DELETE from a REST client such as Fiddler or Postman.
First, you try to access by ip/delete endpoint. I assume you will get an error because you are not using the port of the application (you have to access by ip:port/delete)
You have to know about the usage of DELETE method. When you try to directly access the ip/delete endpoint, your browser will set it as GET method while in your application, there is not GET method for ip/delete

Use Ajax return value in Jade file

I am using ExpressJS together with the Jade template engine. I am trying to do the following:
In a Jade file, I extract a variable which I need in a JavaScript file. In this JavaScript file, I send an Ajax request to the Express server. This returns some data and I would like to put this data in another variable which I can use again in my Jade file.
Here is my code:
Jade file:
script.
var userID = '#{userObject.ID}'; //Extract variable
script(src='/javascripts/account.js') //needed in this file
p
| #{papersObject} //This should be the result from the Ajax request
Ajax request:
$(document).ready( function() {
$.ajax({
url: '/accountdata',
/* jshint ignore:start */
data: {'personId': userID},
/* jshint ignore:end */
dataType: 'JSON',
success: function(data, status, jqXHR) {
var papersObject = JSON.stringify(data.result);
}
});
});
app.js:
var accountData = require('./routes/accountdata');
app.use('/accountdata', accountData);
Route:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
data = //Some database function
res.send({result: data});
});
module.exports = router;
Why is #{papersObject} not showing on my page? How can I get this to work?
Your server side code and client side code run on different computers. The Jade template is processed before the Ajax request is even sent.
If you want to add the data to the page, then you need to use DOM manipulation to do so.
e.g. with append()

Categories

Resources