Node.js Express.js Send Jquery Ajax Post throws Constant Error - I'm stuck - javascript

I'm trying to make a very simple return coming from Node.js to Ajax. I'm using Express.js to make this possible.
I have code from the previous route that I did in order to write and manage JSON files and it works just fine.
The problem comes from the second route that always throws an error when I'm trying to make it return something with the JQuery ajax success method. It is the most simple form of send that I found but still doesn't work.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test 2</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>
<body>
Cod: <input type="text" name="cod" id="cod">
Text: <input type="text" name="text" id="text">
<button id="boton">PRUEBA</button>
<button id="getText">GET TEXT</button>
<script>
$('#boton').click(function() {
let cod=$('#cod').val();
let text=$('#text').val();
console.log(cod);
console.log(text);
$.ajax({
type: 'POST',
data: {
cod: cod,
text: text,
},
url: 'http://localhost:1337/prueba'
});
});
$('#getText').click(function() {
$.ajax({
type: 'POST',
data: {
},
success: (result) => {
console.log(result);
},
error: (result) => {
console.log('ERROR');
},
url: 'http://localhost:1337/getText'
});
});
</script>
</body>
</html>
app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/prueba', function(req, res) {
// ... First Route. The code here works just fine so I don't add it here.
});
app.post('/getText', function(req, res) {
let text = "Hola mundo";
console.log(text);
res.send(text);
});
app.listen(1337, () => console.log('Started server at http://localhost:1337!'));
When you click the 'GET TEXT' Button it enters inside the '/getText' route in app.js and console.logs the text on the node.js terminal so that's not the issue.
The issue seems to come from the res.send() function.
In the browser console it logs 'ERROR' as it appears in the ajax error method associated to the 'GET TEXT' Button. I can't find a way to make it return success.
Could anyone help me? I'm so stuck with this project for work.

looks like a CORS issue... do you serve index.html from the same location?
It works serving index.html from node
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/prueba', function(req, res) {
// ... First Route. The code here works just fine so I don't add it here.
});
app.post('/getText', function(req, res) {
let text = "Hola mundo";
console.log(text);
res.send(text);
});
app.get('*', function (req, res) {
res.sendFile('index.html', {root: '.'})
})
app.listen(1337, () => console.log('Started server at http://localhost:1337!'));
There are several options for node/express, e.g. express middleware

Related

I'm trying to build a simple To Do list in express, but I can't get my 'delete' button to work

I'm trying to make a simple to do list and I can't figure out the "delete" button. I don't get any errors, the buttons just doesn't do anything. I tried a lot of things but just can't seem to get it working. I'm not sure if the problem is with form action in the ejs file or with the app.delete in my index.js or both. Thank you in advance!
ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do List</title>
</head>
<body>
<h1>To Do List</h1>
<form action="/todo" method="post">
<input type="text" name="task">
<button>Add</button>
</form>
<ul>
<% for(let c of todos) { %>
<li>
<%= c.task %>
<form action="/todo/<%=c.id%>?_method=DELETE" method="POST"><button>Delete</button></form>
<%= c.id%>
</li>
<% } %>
</ul>
</body>
</html>
index.js file:
const express = require('express');
const app = express();
const path = require('path');
const methodOverride = require('method-override');
const { v4: uuid } = require('uuid');
uuid();
app.use(methodOverride('_method'));
app.use(express.urlencoded({ extended: true }));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
let todos = [
{
id: uuid(),
task: '1st task, testing'
}
]
//TO DO INDEX
app.get('/todo', (req, res) => {
res.render('todo', { todos });
})
//CREATE NEW TASK
app.post('/todo', (req, res) => {
const { task, id } = req.body;
todos.push({ task, id: uuid() });
res.redirect('todo')
})
//DELETE TASK
app.delete('/todo/:id', (req, res) => {
const { id } = req.body;
todos = todos.filter(c => c.id !== id);
console.log(todos);
res.redirect('/todo')
})
app.listen(3000, () => {
console.log('LISTENING ON PORT 3000')
})
You have configured the delete route in your express app with method type DELETE that is app.delete(…), but in your html form
<form action="/todo/<%=c.id%>?_method=DELETE" method="POST">
The method is mentioned as POST. So express is not accepting it.
Form in html allows only GET and POST request.
You’ll need to trigger those delete api calls using fetch api or jquery or ajax.
Also i am not sure why that _method=DELETE is written in form action. According to me it not need there if your frontend is jinja/Django. If it’s something else then I’m not sure.
To get more insights about why it isn’t working, open the network tab in the browsers console and click your button. It should send a network call to you backend and you should be able to see there why backend isn’t doing anything for that call.
SOLVED IT
I just had to change const { id } = req.body; to const { id } = req.params;

Undefined body from post request in nodejs

I created the API in node js and in the POST method getting the body as undefined. How can I get the value that is passed using the fetch?
code for NodeJs-------------------------------------------
const express=require('express');
const app=express()
const port=3000
const fs=require('fs');
app.get('/',(req,res)=>{
res.send('hello world!');
});
app.get('/movies',(req,res)=>{
fs.readFile(__dirname+'/movies.json','utf-8',(err,data)=>{
res.send(data);
});
});
app.post('/movies',(req,res)=>{
console.log(req.body);
});
app.listen(port,()=>{
console.log(`app listening at http://localhost:${port}`)
});
code for HTML-------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form onsubmit="submitted(event)">
<input id="field" type="text" required="true">
<button type="submit">save</button>
</form>
</body>
<script>
function submitted(e){
e.preventDefault();
const value=document.getElementById('field').value;
await fetch('http://localhost:3000/movies',{
method:'POST',
body:{value},
mode:'no-cors',
headers:{
"Content-Type" : "application/json",
'Access-Control-Allow-Origin':'*'
}
});
}
</script>
</html>
Well you have got 2 problems:
1 Problem:
You need to stringify your body like
body:JSON.stringify({value})
2 Problem:
In express you need to parse your body. For that express provides .json()
const express=require('express');
const app=express()
const port=3000
const fs=require('fs');
app.use(express.json())
You need to use a middleware to parse the body correctly. It looks like you're sending JSON, so you'll need the bodyParser middleware provided by express.

Not able to add another JSON object while checking this API in Postman

I was trying to put another JSON object through Postman in an API that I have built.
It was a tutorial from Mosh Hamedani's YT channel where he was teaching about how to make a API using Node.js, Express and Postman.
Throughout the video everything he showed worked pretty good, but only in this section this code is not able to take a POST request in Postman.
As soon as I select Body > Raw and send the request after pasting the localhost URL in postman, it is coming up with an error.
The whole thing is mentioned underneath.
This is the code for the API
`const express = require('express');
const app = express();
app.use(express.json());
const courses = [
{ id: 1, name: 'courses1'},
{ id: 2, name: 'courses2'},
{ id: 3, name: 'courses3'},
];
app.get('/', (req, res) => {
res.send('Hello World');
});
app.get('/api/courses', (req,res) => {
res.send(courses);
});
app.post('/api/course', (req,res) => {
const course = {
id: course.length + 1,
name: req.body.name
};
courses.push(course);
res.send(course);
});
app.get('/api/courses/:id', (req,res) => {
const course = courses.find(c => c.id === parseInt(req.params.id));
if (!course) res.status(404).send('the course with the given ID was not found.');
res.send(course);
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));`
Trying to add another JSON object by using this code in postman
`{
"name": "courses"
}
`
And postman terminal is returning this error:
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /api/courses</pre>
</body>
</html>`
How do I fix this?
Postman show 'Cannot POST /api/courses', meanwhile in your code, you define to use GET on 'api/courses'.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /api/courses</pre>
</body>
</html>
So, you can check further about that
// this is only GET
app.get('/api/courses', (req,res) => {
res.send(courses);
});
// this is use /api/course, not /api/courses
app.post('/api/course', (req,res) => {
const course = {
id: course.length + 1,
name: req.body.name
};
courses.push(course);
res.send(course);
});

Express how to re-direct json data through different endpoints

I'm pretty new to using express and the responses here on StackOverflow have been very confusing. What I have is JSON data that I am retrieving using app.get(). What I want is to modify this data and send it to my index.html file. I know that I can simply use the fetch function to get the data in my index file from the get endpoint but I need to use both the app.post() and app.put() function.
I'm having trouble understanding your question.
Here's a sample code that uses axios and plain vanilla javascript to get some data from backend and then in frontend, you can modify the data. You can replace axios for fetch and it'll still work.
app.js
const express = require("express");
const bodyParser = require("body-parser");
const port = 8000;
const app = express();
/* Simulating data, a better approach would be to use some storage like MySQL... */
let data = {
name: "Elon Musk",
age: "48",
height: "1.88m"
};
app.use(express.static("public"));
/* body-parser is required so the server can parse the data sent. */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
/* get the data... */
app.get("/api/mydata", function(req, res) {
return res.json(data);
});
/* this is where the client will post the data */
app.post("/api/newdata", function(req, res) {
data.name = req.body.name;
data.age = req.body.age;
return res.json("OK!");
});
app.listen(port, function() {
console.log("Listening on 8000");
});
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="name" placeholder="Name..." value="">
<input type="text" id="age" placeholder="Age..." value="">
<button type="button" id="setValues">Change values!</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js"></script>
<script>
window.addEventListener("load", function() {
axios.get("/api/mydata").then(function(res) {
document.getElementById("name").value = res.data.name;
document.getElementById("age").value = res.data.age;
})
});
document.getElementById("setValues").addEventListener("click", function() {
axios.post("/api/newdata", {
name: document.getElementById("name").value,
age: document.getElementById("age").value
}).then(function(res) {
console.log("Sent!");
})
})
</script>
</body>
</html>
If you have any questions, let me know!

Redirect to new page after AJAX post request using express

I need to make a button that on click redirects me to a new page (localhost:1337/LEDon) and logs some data to the console. However, I can't get the button click to load a new page.
Here's my code -
app.js
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + '/view.html');
});
app.post('/LEDon', function(req, res) {
console.log('LEDon button pressed!');
res.sendFile(__dirname + '/success.html');
});
app.listen(1337);
clientside.js
$('#ledon-button').click(function() {
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon'
});
});
view.html
<!DOCTYPE html>
<head>
</head>
<body>
<button id='ledon-button'>LED on</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src='clientside.js'></script>
</body>
</html>
success.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Success page</title>
</head>
<body>
LEDon button pressed!!
</body>
</html>
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon',
success:function(data, code, jqXHR) {
window.location.pathname = "success.html"
}
});
and your node:
app.post('/LEDon', function(req, res) {
console.log('LEDon button pressed!');
res.status(200)
res.sendFile(__dirname + '/success.html');
res.end()
});
Is one way of doing it, provided this is the only functionality you want for it. Otherwise you can send a 3XX HTML Status code and the browser will deal with it for you, I believe

Categories