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

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);
});

Related

How can I send a POST request to display a message to an html file using axios?

I'm using the weatherstack API and want to send the current temperature of a given city to a simple form in html using the POST method in express (or axios, if possible).
I tried to use the GET method in axios to consume the API and the POST method in express to send the result once the user enters the city they want in the search bar. The code is the following:
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const axios = require('axios');
const access_key = '...'
app.use(bodyParser.urlencoded({extended: false}));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// Successful GET in the console
// axios.get(`http://api.weatherstack.com/current?access_key=${access_key}&query=Dallas`)
// .then(response => {
// const apiResponse = response.data;
// console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
// }).catch(error => {
// console.log(error);
// });
// ----The problem-------
app.post('/', async function (req, res) {
const{response} = await axios(`http://api.weatherstack.com/current?access_key=${access_key}&query=${req.body.cityName}`)
res.send(`<p>Current temperature in ${req.body.cityName} is ${response.current.temperature} ℃</p>
<a href = '/'>Back</a>`)
});
//------------------------
app.listen({port: 4000}, () => {
console.log("Server running on localhost:4000");
});
The website
<!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>Weatherstack</title>
</head>
<body>
<form action="/" method="post">
<p>Inform the city</p>
<input name="cityName">
<button type="submit">Send</button>
</form>
</body>
</html>
But when I run the server I get this error:
How can I solve that?
Axios return the AxiosResponse object.
export interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
config: AxiosRequestConfig<D>;
request?: any;
}
the content of your response is within the data object.
const { data } = await axios(
`http://api.weatherstack.com/current?access_key=${access_key}&query=${req.body.cityName}`
);
res.send(
`<p>Current temperature in ${req.body.cityName} is ${data.current.temperature} ℃</p><a href = '/'>Back</a>`
)
Or
const response = await axios(
`http://api.weatherstack.com/current?access_key=${access_key}&query=${req.body.cityName}`
);
res.send(
`<p>Current temperature in ${req.body.cityName} is ${response.data.current.temperature} ℃</p><a href = '/'>Back</a>`
)
I tested this code, and it works fine.

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;

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

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

Unable to access API created on local node server

I created a simple API on a node server. The server is running on the port 9000. I created an endpoint called getUserDetails and I'm passing a simple object. The problem is I can access the API from the browser by entering the full URL 'http://localhost:9000/getUserDetails'.
But I cannot access the API in another HTML file. To elaborate, I created a simple HTML file to test out this API.
My node server:
const app = express();
app.get('/getUserDetails', (req, res) => {
res.send({
firstname : 'Giri',
secondname: 'Aakula',
dob: '15-09-1997',
age: 22,
qualification : 'Graduate',
status : 'pass'
})
})
app.listen(9000);
My HTML file
<!DOCTYPE html>
<html>
<head>
<title>Test page</title>
<style>
h1{
font-size: 50px;
}
</style>
</head>
<script>
fetch('http://localhost:9000/getUserDetails')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
</script>
<body>
<h1>This is a test page</h1>
</body>
</html>
I forgot to add cors. By adding this one line fixed my issue.
const express = require('express');
const app = express();
app.get('/getUserDetails', (req, res) => {
//this is the updated line
res.setHeader('Access-Control-Allow-Origin', '*');
res.send({
firstname : 'Giri',
secondname: 'Aakula',
dob: '15-09-1997',
age: 22,
qualification : 'Graduate',
status : 'pass'
})
})
app.listen(9000);

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!

Categories