POST http://127.0.0.1:5500/add 405 (Method Not Allowed) - javascript

Could you help me solve this error? It seems that I can not connect between server.js and app.js.
What I want to do is: display the result of the postData('/add', {answer:42}); and postData('/addMovie', {movie:'the matrix', score:5}); in the console.
Thank you for your help in advance.
error image
server.js
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');//add
// Start up an instance of app
const app = express();//add
/* Dependencies */
const bodyParser = require('body-parser') //add
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
//we can connect the other packages we have installed on the command line to our app in our code with the .use() method
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');//add
app.use(cors());//add
// Initialize the main project folder
app.use(express.static('website'));
////////////////////creating a local server
const port = 5500;//add
// Setup Server
//////////////////////add
const server = app.listen(port, listening);
function listening(){
// console.log(server);
console.log(`running on localhost: ${port}`);
};
app.get('/all', function (req, res) {
res.send(projectData)
})
// POST route
const data = []
app.post('/add', callBack);
function callBack(req,res){
res.send('POST received');
console.log(data)
}
const movieData = []
app.post('/addMovie', addMovie )
function addMovie (req, res){
movieData.push(req.body)
console.log(movieData);
}
app.js
app.js
[Addition]
Thank you for your feedback!!
I changed the port in server.js, but nothing changed.
port5500

The issue was resolved.
// when using local server ( ≒ server.js in this case)
postData('/add', {answer:42});
postData('/addMovie', {movie:'the matrix', score:5});
// when using live server
postData('http://localhost:5500/add', {answer:42});
postData('http://localhost:5500/addMovie', {movie:'the matrix', score:5});

You need to add an "allow" in the header field to support this or explicitly allow it in your webserver configuration
A lot of the time, this is set up in the configuration of your .htaccess or nginx.conf file (depending on the webserver). It will commonly be found in your RewriteRule section. You can look for a "R=405" flag there.

Related

stuck at building process while hosting on Vercel

I'm using node.js as a server-side to store the API respond, the app is working without any issue but recently I have been trying to host it on Vercel so I ran into many issue, the project get stuck at the building process...
the building output :
Building output
My server.js code :
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const Cors = require('cors');
app.use(Cors());
// Initialize the main project folder
app.use(express.static('website'));
// Setup Server
const port = 8000;
const Server = app.listen(port , run);
function run() {
console.log(`hello there :D`);
console.log(`here is ${port} ready to go`);
}
//GET method
app.get('/all', function(req,res){
res.send(projectData)
console.log(projectData);
})
//POST method
app.post("/addUserComment", function(req,res){
projectData = {
temp : req.body.temp,
date : req.body.date,
feeling : req.body.feeling,
}
console.log(projectData);
res.send(projectData);
})
My working directory and build settings :
Working directory
Build settings
note: server.js is my server-side file, and my website folder includes my app.js file and my HTML, CSS files, also i did try to add Vercel.json file but i couldn't understand how to use it, so if you gonna add this file in your answer please explain how and why
I think you need to remove the build command, because it's now trying to run the server.js file instead of making a build.

How to deploy Node JS app cPanel from localhost to a server

I have created a simple Express JS app. and it is working fine in localhost. when I visit localhost:8000 I see static files (index.html, style.css and frontend.js).
I have tried to deploy that app in a server using cPanel. and I have installed Node app and dependencies using package.json successfully. But when I visit the domain I just see a message (Node JS app is working, Node version is 10.24.1).
How to make my app to point and display the static folder (index.html) and run the app?
My app architecture:
server.js
package.json
public/index.html
public/style.css
public/frontend.js
And here is my server.js startup file:
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Dependencies */
const bodyParser = require('body-parser');
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder
app.use(express.static('public'));
// Setup Server
const port = 8000;
const server = app.listen(port, function(){
console.log(`server running on localhost: ${port}`);
});
//POST Route to store data in the app endpoint, projectData object
app.post('/addData', addData);
function addData (req, res){
let data = req.body;
projectData = data;
console.log(projectData);
}
app.get('/getData', getData);
function getData(req, res) {
res.send(projectData);
}
The problem here is that you are not pointing a route to send the HTML file. Otherwise the client would have to point it to the correct path of the file, Like localhost:3000/index.html.
you need to send it from the server using app.get
app.get("/", (req, res) => {
res.sendFile(__dirname + "path to the file");
});
The problem was that I have created the app in a subfolder of my domain.
But when I have created subdomain and reinstalled the app inside it, the app is pointing to static folder successfully.

How to manage request data on entry file in node js

In Node Js, on the entry file e.g. index.js, How can I get requested data either as Form-data or Form-URL-encoded or Raw JSON data in middleware?
In my project, I am handling various API request,
Few requests contain file type so requesting as form-data.
Few requests do not contain file type so requests are coming as Form-URL-encoded.
Now the main problem is before routing, I need a specific field from req.body in the middleware.
But I am getting req.body as undefined.
For reference here is my index.js file:
const express = require('express');
const app = express();
app.use(express.raw());
app.use(express.urlencoded({ extended: false }));
app.use((req, res, next) => {
const routes_handler = require('./routes/index.js')(app, express, req);
next();
})
app.listen(3000, () => {
console.log("Server running at Port " + 3000);
});
and the routes/index.js file as follows:
module.exports = function (app, express, req) {
console.log(req.body);
//I need here data of req.body for all requests type (form data, URL-encoded, raw JSON)
app.post('/', function (req, res) {
console.log("Here I can get the requested body easily", req.body)
res.send('Hello World');
});
app.post('*', function (req, res) {
res.send({
code: 0,
message: 'No Content',
status_code: 204,
data: {
error: 'API not found!'
}
});
});
}
Also, I know for file type data, POSTMAN will send the request as Form-data, not as Form-url-encoded. So which I should choose Formidable or Multer?
The way you get all the data in index.js is by creating middlewares for your application, every time any routes that go into your application will be passed through this middleware.
Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
The below middleware will simply listen to all routes & adds up request time to request time, here goes the code
let express = require('express')
let app = express()
let bodyParser = require("body-parser")
app.use(bodyParser.json())
let requestTime = function (req, res, next) { // simply updating add the requestBody using the middleware
req.requestTime = Date.now();
req.json_body = req.body;
next()
}
app.use(requestTime) // requestTime is the middleware here
app.get('/', function (req, res) {
var responseText = 'Hello World!<br>'
responseText += '<small>Requested at: ' + req.requestTime + '</small>'
res.send(responseText)
})
app.listen(3000)
Few things to note here
Always add interceptor above all routes
Don't forget to add next() inside the middleware, else it will not go to the next route.
Now, coming to the second part of your question which is accessing body,formdata, etc
You can use body-parser npm module to achieve that, something like this
Starting from Express 4, body-parser comes inbuilt with it, so you can try out something
app.use(express.json());
app.use(
bodyParser.urlencoded({
extended: false
})
);
Now, the last bit, you don't need Multer for formdata, but for file upload like multipart/form-data you will need this. Both are good in their own ways, I would go for Multer.
Hope this will help you :)
I believe the body-parser module is your answer.
https://www.npmjs.com/package/body-parser
Add the following line before the routes in your index.js after installing the body-parser package.
app.use(bodyParser.json())

How to deploy express.js server to Netlify

I am attempting to deploy a Vue.js, Node, Express, MongoDB (MEVN) stack application to Netlify. I successfully deployed the front end of the application to Netlify, and am now attempting to deploy the express server, based on the following serverless-http example: https://github.com/neverendingqs/netlify-express/blob/master/express/server.js
I configured my server to include the serverless-http package:
server.js
const express = require('express');
const app = express();
const serverless = require('serverless-http');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./DB.js');
const postRoute = require('./routes');
mongoose.connect(config.DB, { useNewUrlParser: true, useUnifiedTopology: true }).then(
() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database'+ err)}
);
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/messages', postRoute);
app.use('/.netlify/functions/server', router); // path must route to lambda
app.use('/', (req, res) => res.sendFile(path.join(__dirname, '../public/index.html')));
module.exports = app;
module.exports.handler = serverless(app);
routes.js
const express = require('express');
const postRoutes = express.Router();
// Require Post model in our routes module
let Post = require('./post.model');
// Defined store route
postRoutes.route('/add').post(function (req, res) {
let post = new Post(req.body);
post.save()
.then(() => {
res.status(200).json({'business': 'business in added successfully'});
})
.catch(() => {
res.status(400).send("unable to save to database");
});
});
// Defined get data(index or listing) route
postRoutes.route('/').get(function (req, res) {
Post.find(function(err, posts){
if(err){
res.json(err);
}
else {
res.json(posts);
}
});
});
module.exports = postRoutes;
I then re-deployed my application to Netlify, but the server does not seem to run in Netlify. This server is in a folder in project root of my vue.js app. Should I instead run the server as a separate site in Netlify? If not, what should I do in order to get the server to run when deployed in Netlify?
It's been a while, but here goes.
Netlify hosting is for the Jamstack, as they say, i.e. only static files, no processing on the server. The idea is to make use of other mechanisms to get your data dynamically, such as APIs hosted elsewhere, which you query straight from the browser, or when you build your site.
Most likely you actually had to deploy your express.js app as a Netlify Function, instead. Check Netlify's blog post on running express apps on their functions.
I had a similar issue, just that my server wouldn't connect to the routes locally, the major difference between my code and yours was that I had to do
const router = express.Router()
and then switched app.use() with router.use()
Like I said, that's for when the localhost says "cannot GET /* a defined path */"
P.S. As a side note, you don't need explicit bodyParser in recent express, express.json() works fine instead.

Passing req.body through Express middleware to routes

I'm using the body-parser npm package to parse POST data in Application/JSON format and using a few different express routers to modularize the routes I'm creating. Here's the important info in my main server.js file:
server.js
var express = require('express');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
// I'm using a sessionId to identify a person in this dummy app instead of adding in authentication. So the API call is sent to http://localhost:5000/johndoe/todo
app.use('/:sessionId/todo', require('./routes/todoRoutes'));
var port = process.env.PORT || 9191;
app.listen(port, function () {
console.log('Express server listening on port ' + port);
});
todoRoutes.js:
var todoRouter = require('express').Router();
todoRouter.post('/', function (req, res) {
console.log("This is the post data:");
console.log(req.body);
});
module.exports = todoRouter;
req.body seems to be getting lost through the middleware; it logs {} to the console. However, on a whim I added the following to my bodyParsing middleware in server.js:
app.use(bodyParser.json(), function (req, res, next) {
next();
});
And now it's passing req.body through to todoRoutes.js. (It now logs {title: 'Testing'}, etc. to the console like I need it to.)
What's going on here? And what's the best way to structure this so that it works the way it's supposed to? I'm new to Express, so I admit I could be structuring this all wrong.
Ugh, nevermind. I was an idiot and found that the Content-Type Header of application/JSON got turned off in Postman (read: I must have turned it off at some point) and so the bodyParser was never being used.
Dammit.
Thanks for the help to those who responded!

Categories