For some reason when I set my app in test.js like this:
const app = express();
I get a 404 error for all tests.
However, when I set it like this
const app = 'http://localhost:3000'
all tests pass.
I'm aware though that this is not the best way to declare app in a testing environment. how can I avoid using a fix path like localhost ?
example:
const express = require('express');
const app = express();
// const app = 'http://localhost:3000'
const chai = require("chai");
const expect = chai.expect;
const request = require('supertest');
it('For all bookings', function (done) {
request(app)
.get('/bookings')
.end(function (err, res) {
expect('Content-Type', /json/)
expect(res.statusCode).to.be.equal(200);
done();
});
});
that way I get Uncaught AssertionError: expected 404 to equal 200
but if I uncomment const app = 'http://localhost:3000' to use it instead of const app = express(); then the test passes.
const app = express() creates dummy Express instance with no routes. It cannot respond to a request to /bookings endpoint because there's no such endpoint.
That http://localhost:3000 works means that an application that has has /bookings route is currently running.
In case application instance is provided to Supertest's request, an instance of the application that has /bookings route should be imported:
const app = require('./app');
if we did this in the test file
const app = express();
it means that we create brand new express application with no routes defined. The correct way is to use same express application not create a new one.
In order to do that, we can export the express app and refer it from the test file.
// index.js
const express = require('express')
const app = express()
const port = 3000
app.get('/bookings', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
module.exports = app; // export express app
Meanwhile for test file
// test.js
...
const app = require("./index"); // import the app
it("For all bookings", function(done) {
request(app)
.get("/bookings")
.end(function(err, res) {
console.log(res);
expect("Content-Type", /json/);
expect(res.statusCode).to.be.equal(200);
done();
});
});
Hope it helps
Related
I'm building an API for my web app and I was able to successfully send requests to the routes in Post.js when they only had url params. But when I try to create a route like '/allposts' (the last endpoint in Post.js) , I receive a 404 error message on postman. Here's my code:
router.post('/', (req, res) => {
// Endpoint 1 code here
})
router.get('/:id', (req, res) => {
// Endpoint 2 code
})
// This is the route that I can't to send requests to
router.get('/ap', async(req, res) => {
try{
const ap = await P.find()
res.send(ap)
} catch(error){
log(error)
res.status(500).send("error")
}
})
server.js
const express = require('express')
var cors = require('cors')
const fs = require('fs');
const path = require('path');
var app = express()
app.use(express.static(path)
app.use(cors())
const bodyParser = require('body-parser')
app.use(bodyParser.json());
var p = require("./routes/P.js");
app.use('/post', p);
const PORT = process.env.PORT || 3001
app.listen(port, () => {
log(`Listening on port ${PORT}...`)
});
When I send a request to http://localhost:3001/post/ap, I'm getting the a 404 Not Found error, but the first two routes work fine. It seems like routes with url params work, but the allposts route does not. Any help would be greatly appreciated. Thanks.
Main problem is the order of the routes.
router.get('/:id') will be initialized before router.get('/allposts'). So when you want to access /allposts the first router will catch it.
You need to switch the init order.
First router.get('/allposts') then router.get('/:id').
So I am starting a node.js app, and familiarizing myself with the basics. I have installed express, and am using the get function to create a route and send a response.
However, on entering the webpage on the browser, the page keeps loading and does not give a response. Any idea on what I am doing wrong here? Even the request body does not show up on the logs, so it looks like its not entering the get function.
Below is the code. Any help would be appreciated.
const http = require("http");
const express = require("express");
const bodyparser = require("body-parser");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
console.log(req.body);
res.send("XYZ Homepage");
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
I use node-fetch for make requests to localhost.
I want to use get method for get specific file content.
An example: my node.js server is a file called app.js, and in the same folder there is a file called config.json, so I want to get (from a discord bot made with discord.js) the content of config.json.
Here my server's code:
const express = require('express');
const app = express();
const fetch = require('node-fetch');
const fs = require('fs')
const port = process.env.port || 1451
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile(`my path`, { 'Content-Type': 'text/html' });
});
app.post('/jsonFile', (req, res) => {
console.log(req.body);
})
app.listen(port, () => console.log(`listening on http://localhost:${port}`));
And here is my discord bot code for connecting to my website:
fetch('http://localhost:1451').then(res => console.log(res))
P.S I use express for node.js servers
Maybe you could use fs.readfile to read that config.json file content and then send that content as a response.
I'm new to nodejs and currently using localhost to run mock APIs.
index.js -
const express = require("express");
const api = require("./routes/api");
const app = express();
// Routes
app.use("/api", api); // route api
routes/api/index.js -
const router = express.Router();
router.get("/path-to-certain-resource", async (req, res) => {
});
//...
router.post("/path-to-another-resource", async(req,res) => {
});
I need to create a new API using a predefined url -
e.g. https://example.com/api/v1/users
How can I do this?
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