I got this error "Cannot GET /api/data"
it s working good on my local host , but when I upload it to server it show me this error,
this is a simple code for testing that also show me the same .
my index page
const express = require('express');
const bodyparser = require('body-parser');
const mysql = require('mysql');
const port = 4000;
const route = require('route');
const data = require('./routes/data.js');
const app = express();
app.use(bodyparser.json());
// parse application/x-www-form-urlencoded
app.use(bodyparser.urlencoded({ extended: false }));
// parse the raw data
app.use(bodyparser.raw());
// parse text
app.use(bodyparser.text());
app.use('/data', data);
app.listen(port, () => {
console.log("working");
});
/routes/data.js file
const express = require('express');
const router = express.Router();
const add = require('../classes/insert');
const bodyparser = require('body-parser');
var con = require('../Modules/connection');
const app = express();
app.use(bodyparser.json());
// parse application/x-www-form-urlencoded
app.use(bodyparser.urlencoded({ extended: false }));
// parse the raw data
app.use(bodyparser.raw());
// parse text
app.use(bodyparser.text());
app.get("/",(req, res)=>{
res.send("hello");
});
module.exports = router;
app.use('/data', data)
This will only work on /data route. If you want this work on /api/data, use the following snippet.
app.use('/api/data', data)
this error may be comming because of the file path. Try using __dirname in spite of ./ and also check your file structure.
Hope this works.
Related
I have a node express set up.
While using Postman, Iam able to see data sent through x-www-form-urlencoded but the same is not being shown through form-data.
below are the codes
Server.js
const express = require('express')
var cors = require('cors')
const app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
var cookieParser = require('cookie-parser')
app.use(cookieParser())
app.use(cors())
const index = require("./routes/index")
app.use("/", index)
const port = process.env.PORT || 3060;
app.listen(port, function listenHandler() { console.log(`Running on ${port}`) });
Index.js
const express = require('express')
const router = express.Router()
var pool = require('./mysqlConnector')
const asyncMiddleware = require('./asyncMiddleware')
const func = require('./functions')
const time = new Date().toISOString().slice(0, 19).replace('T', ' ')
const nodemailer = require("nodemailer");
router.use('/auth', require('./auth')
Auth .js
const express = require('express')
const router = express.Router();
var pool = require('./mysqlConnector')
const asyncMiddleware = require('./asyncMiddleware')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const nodemailer = require("nodemailer");
const func = require('./functions')
router.post('/register', asyncMiddleware( async(req, res, next) => {
res.send({ success: true, message: req.body })
}))
You should use Multer to handle form-data.
Multer is a node.js middleware for handling multipart/form-data
body-parser middleware can't handle multipart/form-data.
This does not handle multipart bodies, due to their complex and typically large nature.
In case you need to handle a text-only multipart form, you should use the .none() method:
E.g.
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer();
const app = express();
app.use(upload.none());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/auth/register', (req, res) => {
res.send({ success: true, message: req.body });
});
const port = process.env.PORT || 3060;
app.listen(port, function listenHandler() {
console.log(`Running on ${port}`);
});
postman:
I have a react app front end posting data to my server(use express) deployed on Heroku. Code works well when both client and server running on localhost, but when it's on Heroku, the req.body always gets empty object {}.
Can anyone point out what's going wrong here? Thanks in advance :)
React code:
axios.post("/api", data, {headers: { "Content-Type": "application/json;charset=utf-8" }})
Express code:
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(
cors({origin: URL,credentials: true}));
app.post("/api", (req, res) => {const data = req.body; console.log(data);};
This run perfectly on my computer. The log and the response works just fine. Hope it helps. I think the problem could be you are sending a GET request instead of a POST request.
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors({origin: new URL('http://localhost:3000'), credentials: true})) // Add this 'new' keyword to URL
app.post("/api", (req, res) => {
const data = req.body
console.log(data)
res.send(data) // Added this to allow request to end
})
// Added this part to start the server listen.
const port = process.env.PORT || 3000
app.listen(port , () => {
console.log('Server is running on port '+3000)
})
I am beginner in node js, i worte a code to get the form data from html using express and it allways shows the warning.
"body-parser deprecated undefined extended: provide extended option app.js:11:17"
here is my code
const express = require('express')
const path = require('path')
const app=express()
const port=process.env.PORT || 3000
const publicDirectoryPath = path.join(__dirname, '')
app.use(express.static(publicDirectoryPath))
app.use(express.urlencoded())
app.use(express.json())
app.get('',(req,res)=>{
res.render('index')
})
app.post('/login',(req,res)=>{
try{
console.log(req.body)
res.send('thankyou for submission')
}catch(error){
res.send()
}
})
app.listen(port,()=>{
console.log('server started to'+port);
})
you need to replace
app.use(express.urlencoded())
with
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
and dont forget to require bodyparser
var bodyParser = require('body-parser');
You have to provide the option "extended" when using the bodyParser since the default value is going to change. Use this on line 11:
app.use(bodyParser.urlencoded({ extended: true }));
Also include the bodyParser module with:
const bodyParser = require('body-parser');
When I send a POST request using postman to localhost:8080/api/newUser with request body:
{name: "Harry Potter"}
At server end console.log(req.body) prints:
{ '{name: "Harry Potter"}': '' }
server.js
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
app.use('/', express.static(__dirname));
router.use(function(req, res, next) {
next();
});
router
.route('/newUser')
.post(function(req, res) {
console.log(req.body);
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
app.use('/api', router);
app.listen(8080);
What am I doing wrong?
In express.js the order in which you declare middleware is very important. bodyParser middleware must be defined early than your own middleware (api endpoints).
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
app.use('/', express.static(__dirname));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
router
.route('/newUser')
.post(function(req, res) {
console.log(req.body);
});
app.use('/api', router);
app.listen(8080);
Change the request header
'Content-Type':'application/json'
So that bodyParser can parse the body.
*That is what works for me. i am using angular 2+ with express(body-parser)
I spent quite a bit of time trying to figure out how to pass objects from Axios as key-value pairs and eventually decided to go with an alternative because setting the Content-Type: "application/json" retuned an empty object.
If the above options don't work for you, I would consider:
Extracting the key (which should contain the entire
object)
Parsing the key
Accessing the values of the newly created objects
This worked for me:
var obj = (Object.keys(req.body)[0])
var NewObj = JSON.parse(obj)
var name = apiWords["Key1"]
var image = apiWords["Key2"]
The relevant part of my app.js is as follows
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var routes = require('./config/routes);
app.use('/', routes);
My route file is:
var express = require('express');
var router = express.Router();
var upgradesController = require('../../app/controllers/upgrades.server.controller');
// This should receive POST requests
router.post('/api/upgrades/device', upgradesController.create);
module.exports = router;
And finally my controller is
exports.create = function(req, res) {
res.send(req.body);
}
But this sends nothing. It's always an empty JSON value. I'm using PostMan for testing:
What is happening?
You're sending form-data, switch to x-www-form-urlencoded instead. You can also send "raw", and input valid JSON.