Expressjs server and external api calls - node.js

I'm new to frontend development and express server. When I tried to start an express.js server with react (with axios calls to external apis), it seems express.js is adding 'localhost:3000' in front of the external API calls so they fail.
In my server.js:
const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '.', 'dist');
const port = process.env.PORT || 3000;
app.use(express.static(publicPath));
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
app.listen(port, () => {
console.log('Server is up!');
});
Which leads to the API call to www.example.com/api/ to become http://localhost:3000/www.example.com/api/
I also tried to filter the req by writing:
app.get('*', (req, res) => {
if (req.url.match(/\/api\//) === null) {
res.sendFile(path.join(publicPath, 'index.html'));
}
});
But it does not change things...
Can anyone help out this newbie that is me?
Update1 Adding the code for calling the api:
This is the api call:
const getSomething = () => {
try {
const url = endpoints.GET_SOMETHING;
return axios.get(url);
} catch (err) {
console.log(err);
}
};
endpoints.GET_SOMETHING is the api URL: www.example.com/api/getSomething

You need to put a / in the url
app.get('/*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
and also your endpoint url should start with https://, http:// or //

Related

Unexpected response on root endpoint using Express

I am new to express and using it for a game interaction. My problem is that when accessing root url I expected a simple hello world to come up, but I'm being served the html from a different endpoint.
On my server.js, I have:
const path = require('path');
const express = require('express')
const app = express()
app.use(express.json())
const { resetGame, takeTurn, checkWinner } = require('./logic.js');
const PORT = 8080
app.use(express.static('public'));
Then, I've set the following requests:
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.get('/connect4', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
app.post('/connect4', (req, res) => {
const bodyInfo = req.body
let clickedRow = bodyInfo.row
let clickedColumn = bodyInfo.column
currentState = takeTurn(clickedRow, clickedColumn)
currentState = checkWinner()
res.send(currentState)
});
app.post('/reset', (req, res) => {
currentState = resetGame()
res.send(currentState)
});
app.get('/fail', (req, res) => {
res.status(400)
res.json({ errorMessage: "missing parameters" })
})
app.listen(PORT, () => {
console.log(`Express server up on port: ${PORT}`)
})
When starting the server on my local and accessing localhost, I expected:
localhost:8080/ > to give me "Hello, World!"
localhost:8080/connect4 > to serve me html and run game functionalities
Although I have 2. working fine, 1. is also serving me the html and I can run the game functionalities there, as in / is giving me the same as /connect4.
Any ideas on why is this happening and what could I do to if I want that hello world in root?

localhost infinitely loading nodejs

I am starting to learn Node.js and as the first step I am deploying my server using node.js
This is my code:
const express = require("express");
const { readFile } = require("fs/promises");
const app = express();
app.get('/', (request, response) => {
readFile('./home.html', 'utf8', (err, html) => {
if(err){
response.status(500).send("Sorry, we are out of order");
}
response.send(html);
})
})
app.listen(3000, () => console.log(`App available on http://localhost:3000`))
But the when i click that link, the localhost seems to be loading infintely.I have tried with different ports.I am using powershell for this and not a WSL.What seems to be the problem here?
Try to use node path module, and put your html file into root directory. It works like a charm.
const express = require("express");
const path = require("path");
// const { readFile } = require("fs/promises");
const app = express();
// app.get("/", (request, response) => {
// readFile("./home.html", "utf8", (err, html) => {
// if (!err) {
// response.status(500).send("Sorry, we are out of order");
// }
// response.send(html);
// });
// });
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "/home.html"));
});
app.listen(3000, () => console.log(`App available on http://localhost:3000`));

Why my react project server route not working when deploy to heroku

Everything works fine when I work on localhost:8000 but when I deployed it to heroku all the routes are not working
Here is my server.js:
const express = require("express"),
app = express(),
cors = require("cors"),
port = process.env.PORT || 8000,
db = "beuter",
path = require("path"),
server = app.listen(port, () => console.log(`Listening to on port ${port}`));
app.use(cors());
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static('beuter/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'beuter', 'build', 'index.html'));
})
}
require("./server/config/database.config")(db);
require("./server/routes/product.route")(app);
and here is my server/routes/product.route.js:
const product = require("../controllers/product.controller");
var path = require("path");
module.exports = (app) => {
app.get("/api/products", product.index);
// Create a product
app.post("/api/products", product.create);
// Get one product by title_url
app.get("/api/products/:title_url", product.show_title_url)
// Delete a product
app.delete("/api/products/:id", product.deleteProduct)
//Edit a product
app.put("/api/products/:id", product.update)
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'beuter', 'build', 'index.html'));
})
};
This is the error in my chrome console
Access to XMLHttpRequest at 'localhost:8000/api/products' from origin 'https://thebeuter.herokuapp.com' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Here is the github project if you want to look over my code:
https://github.com/nathannewyen/the-beuter
Updated:
Here is my Form.jsx from front-end:
const addProduct = (e) => {
e.preventDefault();
const product = {
title,
title_url,
price,
description1,
description2,
description3,
description4,
description5,
img_url1,
img_url2,
img_url3,
img_url4,
size,
size2,
fit,
fit2,
category,
};
axios
.post("https://localhost:8000/api/products", product)
.then((res) => {
if (res.data.errors) {
setErrors(res.data.errors);
} else {
navigate("/");
}
})
.catch((err) => console.log(err));
};

App.js to redirect to a module

I am debugging into a NODE JS application and I am very new to node js. I have a REST module file
students.js
module.exports = function (service) {
/**
* Retrives data from DB
*/
service.get('/mobile/students', function (req, res) {
res.set('Content-Type', 'application/json')
.status(200)
.json(DBHelper.getAllStudents());
});
service.post('/mobile/students', function (req, res) {
res.status(200).json(data);
});
});
To run it locally I am using the following app.js
const express = require('express');
const app = express();
var routes = require('./students');
app.get('/', function (req, res) {
res.send('Hello World!')
});
app.listen(3010, function () {
console.log('Example app listening on port 3010!')
});
When I hit
http://localhost:3010/students, I am hitting a 404.
How do I explicit route the path to the student modules?
you need to add routes(app); line after var routes = require('./students'); then Your routes will be mounted..
http://localhost:3010/students if use this it will prompt you again with 404 but if you use http://localhost:3010/mobile/students it will produce desire output..

Express JS node framework did not respond to post() request

I'm following a blog to build my first node API with express framework. But the POST request did not return a response.
const app = express();
require('./app/routes')(app, {});
app.listen(port, () => {
console.log('We are live on ' + port);
});
module.exports = function(app, db) {
console.log('reached2');
app.post('/notes', (req, res) => {
// You'll create your note here.
console.log('reached3');
res.send('Hello');
//res.end();;
});
};
Here are my console logs,
reached1
reached2
We are live on 8000
Here are my dependencies,
"dependencies": {
"body-parser": "^1.17.2",
"express": "^4.15.3",
"mongodb": "^2.2.28"
},
"devDependencies": {
"nodemon": "^1.11.0"
}
Im using the postman client to POST.
I tried replacing the fat arrow operator with an anonymous function but still doesnt work.
Please point the problem in this code.
If you want to keep your routes in a separate file (which is fairly standard practice), then you need to return a router and tell the express app to use it.
app.js
const express = require('express');
const routes = require('./routes')({});
const app = express();
app.use('/', routes);
app.listen(8080, () => {
console.log('Listening on 8080');
})
routes.js
const express = require('express');
module.exports = (db) => {
const router = express.Router();
router.post('/notes', (req, res) => {
res.send('Hello!');
})
// all your other routes here!
return router;
}
Or, alternatively if you want to do it without using using express.Router(), you could pass the app.
app.js
const express = require('express');
const app = express();
require('./routes')(app, {});
app.listen(8080, () => {
console.log('Listening on 8080');
})
routes.js
module.exports = (app, db) => {
app.post('/notes', (req, res) => {
res.send('Hello!');
})
}
Instead of writing route in a function you can use it directly. Below is the code snippet for the same:
const app = express();
app.listen(port, () => {
console.log('We are live on ' + port);
});
app.post('/notes', (req, res) => {
// You'll create your note here.
res.send('Hello');
});

Resources