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
Related
i'm trying to use postman with "post" method , but when i use it i'm getting a 404 not found error.
i will attach my code and a picture of the error
thanks in advance
using React Native
const express = require('express');
const router = express.Router();
router.post('/signup', (req, res) => {
res.send('You made a post request');
});
module.exports = router;
Picture from Postman app with the error
Things to consider are
1. Make sure you have imported the routes in app.js and used them.
2. Your app is running on 3000 port.
const UserRouter = require('./routes/v1');
app.use('/api',UserRouter);
const port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("listening at port",port)
});
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}`)
});
tldr
Ok i've been trying to get a file upload server working for a few days now and evrything i try just returns cannot get.
i'm currently trying the setup below but it is not working
code
here is server.js
const express = require("express");
const upload = require("./upload");
const cors = require("cors");
var router = express.Router();
var app = express();
const server = express();
var corsOptions = {
origin: "*",
optionsSuccessStatus: 200
};
server.use(cors(corsOptions));
router.get("/", function(req, res) {
res.render("index", { title: "Express" });
});
server.post("/upload", upload);
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`listening on port ${port}`);
});
Below is upload.js
const IncomingForm = require("formidable").IncomingForm;
module.exports = function upload(req, res) { var form = new IncomingForm();
form.on("file", (field, file) => {
// Do something with the file
// e.g. save it to the database
// you can access it using file.path
console.log("thisno werk"); }); form.on("end", () => {
res.json(); }); form.parse(req); };
Let's mean server as the result of the const server = require('express')();, and router as the result of const router = require('express').Router();.
server is an instance of your Express server while router is an instance of API endpoints router. You don't only need to write your router router.get();, but you also need to set the appropriate files (so-called controllers) for handling API requests.
So your code should have this line: server.use('/', yourController); or simply server.get('/', handlingFunction); if you don't have API sections.
However, if you use routers, then you need the first variant.
Your POST /upload method works great because it's configured on the app level. But you need to fix your GET / method because it's configured on the router level that is unused in your app.
Source: Express routing
I'm running a node.js rest api with Express v4. All the routes work as expected via localhost debug. But on my server, they don't. The only thing that differs, is that the port listening is done by Phusion Passenger on the server (I can't change that). Here's my app.js:
const express = require('express'),
bodyParser = require('body-parser'),
cors = require('cors'),
helmet = require('helmet'),
http = require('http');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use(helmet());
app.use('/', require('./api/routes'));
var server = http.createServer(app);
var port = 'passenger'; // 3000 on localhost
server.listen(port, function () {
console.log('listening ' + port);
});
Here's a my routes.js that works on local debug, but won't on the server:
var express = require('express');
var router = express.Router();
router.get('/api/test', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('test get works !');
res.end('test get works!');
});
router.post('/api/test', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('test post works !');
res.end('test post works!');
});
module.exports = router;
Here are the logs for localhost (successful routing):
20180107_192254 | /api/test
20180107_192254 | { get: true }
20180107_192254 | test get works !
20180107_192350 | /api/test
20180107_192350 | { post: true }
20180107_192350 | test post works !
The log file of the same process, but done via the remote server (I'm always redirected to the first route, and req.method is always GET). While the 'req.route.path' is the always the good one, it never goes into the expected function:
20180107_192757 | /api/test
20180107_192757 | { get: true }
20180107_192757 | test get works !
20180107_192759 | /api/test
20180107_192759 | { get: true }
20180107_192759 | test get works !
Do you know if I have to update something somewhere (maybe .htaccess, or in the js code)? I couldn't find anything on both the Phusion and the Express doc.
EDIT:
I replace the express router with a direct use of route by the app and it doesn't work.
But I noticed something:
var express = require('express');
var router = express.Router();
router.get('/api/test', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('test get works !');
res.end('test get works!');
});
router.post('/api/test', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('test post works !');
res.end('test post works!');
});
router.get('/api/otherTest', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('other test get works !');
res.end('other test get works!');
});
module.exports = router;
Here, I can go the the first and the third routes. In fact, all GET routes work (and only them). If I do this:
var express = require('express');
var router = express.Router();
router.post('/api/test', function (req, res, next) {
console.log(req.route.path);
console.log(req.route.methods);
console.log('test post works !');
res.end('test post works!');
});
module.exports = router;
I get nothing.
Ok. So I figure it out: my website is rerouting all http:// traffic to https:// traffic, and all requests (GET, POST, PUT,...) sent through http:// are somehow transformed to GET requests.
They are all correct via https://.
I don't know why this is happening, but feel free to give more details about this issue if you do! I'll update when I find out.
i have following problem in my express application for now. I have different services with build in webserver running. The problem is now i need to access it following:
localhost:8888
The normal server can be accessed over localhost:3000.
Is it possible to create something like a proxy to have something like this.
localhost:3000
localhost:3000/admin/chronograf
localhost:3000/admin/mongo
const express = require('express');
const httpProxy = require('http-proxy');
const app = express();
const proxyOptions = {
}
const apiProxy = httpProxy.createProxyServer(proxyOptions);
const serverOne = 'http://localhost:8888';
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.all("/app1", function(req, res) {
console.log('redirecting to Server1');
apiProxy.web(req, res, {target: serverOne});
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
The Problem is that the page is showing put the links of the resources are not rewritten to the new path. I need a config value or some own Implementation to rewrite the urls.
thanks for helping