I'm learning how to build a RESTful api with Node and Express, and I am having an issue with this https request. I am trying to make a GET request to Scryfall's api (documentation here: https://scryfall.com/docs/api), but whenever I run my server and check the browser I get a message stating
"localhost didn’t send any data. ERR_EMPTY_RESPONSE".
As I'm new to using Node and Express, I'm not really sure what I am doing wrong. Here is the code for my server.js and app.js files.
//server.js
const https = require('https');
const app = require('./backend/app');
const port = process.env.PORT || '3000';
app.set('port', port);
const server = https.createServer(app); //pass the express app to the server
server.listen(port);
and
//app.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('https://api.scryfall.com/cards/named?fuzzy=aust+com', (req, res, next) => {
res.send('${res.body.name} is the name of the card!');
});
module.exports = app;
Any help would be greatly appreciated! Thanks in advance!
👨🏫 For an example, you can do it with this code below 👇:
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('/', async (req, res, next) => {
try {
const result = await axios.get('https://api.scryfall.com/cards/named?fuzzy=aust+com');
res.status(200).send(result.data);
}catch(ex) {
console.log(ex.message);
}
});
app.listen(3000, () => {
console.log('Server is up');
})
💡 From the code above, you can call the endpoint: localhost:3000 and than you will get the result.
I hope it's can help you 🙏.
You can easily make a get request like this.
const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
//Expect a JSON body
app.use(bodyParser.json({
limit: '50mb' //Request size - 50MB
}));
app.get('/test', (req, res, next) => {
// do whatever you need here
res.status(200).send("ok");
});
app.listen(port, function () {
console.log(`Server is running.Point your browser to: http://localhost:${port}`)
});
Related
In my html I have,
<input name="password" type="password" required class="form-control" id="exampleInputPassword1">
and in my node I have,
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/login.html', (req, res) => {
res.sendFile('./login.html', {root: __dirname});
})
app.post('/login', urlencodedParser, (req,res)=>{
req.body.password
})
but, the req.body.password is undefined or empty. How do I make it actually grab what the user is inputting? It does not work for any of them but, I just used password as an example. All the packages were downloaded correctly.
Thanks.
I used the following code:
const express = require("express");
const bcrypt = require("bcrypt");
const bodyParser = require("body-parser");
const app = express();
const jsonParser = express.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
// CHANGE THIS TO DATABASE LATER OF USERS
const users = [];
//listen for requests
app.listen(3000);
app.use(express.static(__dirname + "/public"));
app.get("/index.html", (req, res) => {
res.sendFile("./index.html", { root: __dirname });
});
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", jsonParser, (req, res) => {
console.log("Hello");
console.log(req.body.password);
res.json(req.body.password);
});
app.get("/signup.html", (req, res) => {
res.sendFile("./signup.html", { root: __dirname });
});
app.post("/signup", urlencodedParser, (req, res) => {});
app.use((req, res) => {
res.sendFile("./404.html", { root: __dirname });
});
And when I send a POST request to the /login path using the following payload:
{
"password": "Check for Stack Overflow"
}
I get this on the console:
$ node app
Error: ENOENT: no such file or directory, stat '/root/404.html'
Hello
Check for Stack Overflow
I use the following end point: http://2886795314-3000-ollie08.environments.katacoda.com/
And I used POSTMan and got this right now:
Previous Answer...
You have to use res object to send something. For example, to send a JSON structure, you can do:
res.json(req.body.password)
So your code will be:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", urlencodedParser, (req, res) => {
res.json(req.body.password);
});
Also I could see that you are not using a .listen or export of your modules. You may as well need to listen it to a port to run! So use:
app.listen(3000, () => {
console.log("Server started in port 3000!");
});
At the end. So your complete file looks like:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get("/login.html", (req, res) => {
res.sendFile("./login.html", { root: __dirname });
});
app.post("/login", urlencodedParser, (req, res) => {
res.json(req.body.password);
});
app.listen(3000, () => {
console.log("Server started in port 3000!");
});
Also, please consider reading Express "Hello World" example. It has the best example in the easiest way possible from the original documentation.
req.body.password is kind of like a variable. It 'returns' it's value, but you're not doing anything with what it returns.
It's not clear what you mean with return. If you want to log something to a console, you can do that:
console.log(req.body.password);
I spend so much time looking at this.. I am just following udemy tutorial where instructor used exactly below.. BUT when I run it, req.body is empty EVEN though I am sending it from source(I tried from both nodeman and insomnia). I am just posting { "name":"test" }... and it's not getting the req.body...
I console logged just req and do not see the parm 'body'... Can someone please throw me some light here? SO furstrated
const express = require('express');
const app = express();
const port = 8002;
app.post('/', (req, res) => {
console.log(req.body);
});
app.listen(port, () => {
console.log(`port : ${port}`);
})
Try using body-parser for your req.body.
First install the dependency npm install body-parser and then try executing the below code:
const app = express();
const bodyParser= require('body-parser')
const port = 8002;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.post('/', (req, res) => {
console.log(req.body);
});
app.listen(port, () => {
console.log(`port : ${port}`);
})
For more documentation refer: body-parser-documentation
I write this code and req.body is undefined
I want to get post value in my program
can you help me, please?
const express = require('express')
const app = express()
const port = 3000
const crypto = require('crypto');
function sha1(s) {
return crypto.createHash("sha1")
.update(s)
.digest("hex");
}
app.post("/flag", (req, res) => {
console.log(req.body);
});
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
You body-parser npm package
$ npm i body-parser
var express = require('express')
var bodyParser = require('body-parser')
const app = express()
const port = 3000
const crypto = require('crypto');
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
function sha1(s) {
return crypto.createHash("sha1")
.update(s)
.digest("hex");
}
app.post("/flag", (req, res) => {
console.log(req.body);
});
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Instead of using body parser, Express already providing support for that,
import express from "express";
const app = express();
app.use(express.json());
app.use(express.urlencoded());
This should be given before the Api route
Hy there, I'm trying to learn to make a REST API. I have the following code, where I mention that i have no error. When I try to access localhost:3000 nothing happens it's just reloading a blank page. What am I doing wrong?
Servers.js
const http = require('http');
const app = require('./app').default;
const port = process.env.port || 3000;
const server = http.createServer();
server.listen(port);
App.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.status(200).json({
message: 'It works!'
});
});
module.exports = app;
You've not defined any route. Express generator generates the boilerplate code which is use full to start with.
You can also define a route like this:
app.use('/', function (req, res, next) {
return res.render('index', {title: 'DASHBOARD', 'data': ''});
});
Have a look at this doc: https://expressjs.com/en/starter/generator.html
I am trying to post using restler and return the response to client but response never returns .Below is code I am using and response is just hanging
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var rest = require('restler');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = 3001; // can also get it from process.env.PORT
var router = express.Router();
//this is like interceptor for every route to validate all requests, logging for analytics
router.use(function (req, res, next) {
console.log('route intercepted');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/', function(req, res) {
res.json({ message: "welcome to restful node proxy layer to business processes" });
});
router.route('/someroute').post(function(req, res) {
rest.postJson('http://localhost/api/sg', req.body).on('complete', function(data, response) {
console.log(response);
}
).on('error', function(data, response) {
console.log('error');
});
});
app.use('/api', router); //all routes are prefixed with /api
app.listen(port);
console.log("server is running magic happens from here");