Getting cannot POST / error in Express - javascript

I have a RESTful API that I am using postman to make a call to my route /websites. Whenever I make the call, postman says "Cannot POST /websites". I am trying to implement a job queue and I'm using Express, Kue(Redis) and MongoDB.
Here is my routes file:
'use strict';
module.exports = function(app) {
// Create a new website
const websites = require('./controllers/website.controller.js');
app.post('/websites', function(req, res) {
const content = req.body;
websites.create(content, (err) => {
if (err) {
return res.json({
error: err,
success: false,
message: 'Could not create content',
});
} else {
return res.json({
error: null,
success: true,
message: 'Created a website!', content
});
}
})
});
}
Here is the server file:
const express = require('express');
const bodyParser = require('body-parser');
const kue = require('kue');
const websites = require('./app/routes/website.routes.js')
kue.app.listen(3000);
var app = express();
const redis = require('redis');
const client = redis.createClient();
client.on('connect', () =>{
console.log('Redis connection established');
})
app.use('/websites', websites);
I've never used Express and I have no idea what is going on here. Any amount of help would be great!!
Thank you!

The problem is how you are using the app.use and the app.post. You have.
app.use('/websites', websites);
And inside websites you have:
app.post('/websites', function....
So to reach that code you need to make a post to localhost:3000/websites/websites. What you need to do is simply remove the /websites from your routes.
//to reach here post to localhost:3000/websites
app.post('/' , function(req, res) {
});

Related

How can i list data from table in the database in a browser

I'm developing a web application using reactjs nodejs and mysql database.
I want to list the data created in a table i created in the database in the browser via a link(http://localhost:5000/api/v/companies) .What code should i write in a page created in reactsjs?
Here is the code in the file index.js the backend of the table i created :
const express = require("express");
const app = express();
const cors = require("cors");
const pe = require('parse-error');
const logger = require('morgan');
const database = require('./mysql');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false,
limit: '800mb'
}));
// CORS
app.options("*", cors());
app.use(cors());
database.connect(function(err) {
if (err) throw err;
console.log("==> MySQL Connected Successfully!");
// The main page
app.get('/', function (req, res) {
res.json({
version: 'v1',
status: true
});
});
const stations = require('./routes/stations');
const companies = require('./routes/companies');
app.use('/api/v1', [stations, companies]);
});
app.listen(5000, () => {
console.log("Server is running on port 5000");
});
process.on('unhandledRejection', error => {
console.error('Uncaught Error', pe(error));
});
as well as other files created in the backend
const database = require('./../mysql');
/**
* List all companies
*/
const getAllCompanies = async function(req, res, next) {
try {
database.query('SELECT * FROM infos_stations.Companies', function (err, result, fields) {
if (err) throw err;
return res.status(200).json(result);
});
} catch (err) {
return res.status(500).send({
code: 500,
status: false,
data: "Internal Server Error"
});
}
};
module.exports = {
getAllCompanies,
};
In the reactjs application, you have to install any library for HTTP
requests. Axios is a Javascript library used to make HTTP requests
from node.js or XMLHttpRequests from the browser that also supports
the ES6 Promise.
In the backend, You have to create a route that accepts the HTTP request from
Frontend.
app.post('/getdata', function (req, res) {
// database queries etc.
//sending response(database result)at frontend.
}
In reactjs you can create an HTTP request on a button click or can create a
request on component renders using the UseEffect hook.
axios({
method: 'POST',
url: 'htttp//localhost/getdata',
responseType: 'stream'
})
.then(function (response) {
// response.data have all data of database.
//store response data in any reactjs state.
});
Use Map Function of state array in which you store a response that contains all database records. How to map lists How to render an array of objects in React?

Bind problem in SQL query in Node, Express, Mysql2 app

I have been following a tutorial on setting up REST APIs in Node, using Express for an app that accesses an existing MariaDB database. My version only needs to read data and I have the DB co-located with the Node application (same host).
My goal for this entry-level example is to just access the data, using static SQL, so I can see it rendered in the web page by the JSON pritifier.
[Next, I want to present the data in a table (EJS?). Later, when I can get that to work, I'll add form controls (React?) to let a user specify start and end date bounds for the SQL query. Finally I'll aim to render the data as a line graph (D3js).]
The tutorial runs the web server successfully (it returns 'OK' on the base URL), but when I go to URL/solarData it tries an async function to getMultiple rows from the DB, it responds:
Bind parameters must not contain undefined. To pass SQL NULL specify JS null TypeError: Bind parameters must not contain undefined. To pass SQL NULL specify JS null
at /SunnyData/solarViz/node_modules/mysql2/lib/connection.js:628:17
at Array.forEach (<anonymous>)
at Connection.execute (/SunnyData/solarViz/node_modules/mysql2/lib/connection.js:620:22)
at /SunnyData/solarViz/node_modules/mysql2/promise.js:120:11
at new Promise (<anonymous>)
at PromiseConnection.execute (/SunnyData/solarViz/node_modules/mysql2/promise.js:117:12)
at Object.query (/SunnyData/solarViz/services/db.js:6:40)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async Object.getMultiple (/SunnyData/solarViz/services/solarData.js:7:16)
at async /SunnyData/solarViz/routes/solarData.js:8:14
app.js:61
./app.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3800;
const solarDataRouter = require('./routes/solarData');
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
app.get('/', (req, res) => {
res.json({'message': 'ok'});
})
app.use('/solarData', solarDataRouter);
/* Error handler middleware */
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
console.error(err.message, err.stack);
res.status(statusCode).json({'message': err.message});
return;
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});
./routes/solarData.js
const express = require('express');
const router = express.Router();
const solarData = require('../services/solarData');
/* GET solar data. */
router.get('/', async function(req, res, next) {
try {
res.json(await solarData.getMultiple(req.query.page));
} catch (err) {
console.error(`Error while getting solar data `, err.message);
next(err);
}
});
module.exports = router;
./config.js
const env = process.env;
const config = {
db: {
host: env.SUNNY_HOST,
user: env.SUNNY_USER,
password: env.SUNNY_PW,
database: env.SUNNY_DB,
},
listPerPage: env.LIST_PER_PAGE,
};
module.exports = config;
./services/solarData.js
const db = require('./db');
const helper = require('../helper');
const config = require('../config');
async function getMultiple(page = 1){
const offset = helper.getOffset(page, config.listPerPage);
const rows = await db.query(
`SELECT * FROM DTP LIMIT ?,?`, [offset, config.listPerPage]
);
const data = helper.emptyOrRows(rows);
const meta = {page};
return {
data,
meta
}
}
module.exports.getMultiple = getMultiple;
./services/db.js
const mysql = require('mysql2/promise');
const config = require('../config');
async function query(sql, params) {
const connection = await mysql.createConnection(config.db);
const [results, ] = await connection.execute(sql, params);
return results;
}
module.exports = {
query
}
I've left out the ./helper.js
Everything runs fine until I direct the webpage to /solarData. At that point I get the Debug Console (vscode) mentioned up-front
Searching seems to point at a mysql2 shortcoming/bug but not at a practical solution
If you respond, please describe the 'bind' mechanism, as I'm not sure what's going on.
Hope I've put enough info in. Please ask if I need to add anything else.
The error says
Bind parameters must not contain undefined.
It means that in the file ./services/solarData.js on the line
const rows = await db.query(
`SELECT * FROM DTP LIMIT ?,?`, [offset, config.listPerPage]
);
Some of the 2 variables is undefined, you need to check offset and config.listPerPage to be defined.
Just use
console.log('offset: ' + offset)
console.log('listPerPage: ' + config.listPerPage)
and you will find out what is undefined in your case

get method not displaying the data on browser and put showing error on postman

I'm creating an API with JS. While using the get method I'm not receiving the JSON data from the ./personal_data.js file. It's only displaying closed braces as response.
I'm attaching the code and output below. Any suggestions might be helpful.
const express = require('express');
const personal_data = require('./personal_data');
const app = express();
app.listen(3000, () => {
console.log('Listening on port 3000');
});
app.get('/', (req, res) => {
res.json({ Message: 'API is Working' }); // show messsage on serv
});
app.get('/personal_data', (req, res) => {
res.json(personal_data); // send employee json file
});
app.post('/personal_data',(req,res)=>{
res.send('post request')
})
json file with data
OUTPUT
Post man
Make sure you're exporting your data correctly. Use module.exports = ... instead of module.export = ... in your personal_data.js. Don't forget to restart your server once it's updated.
Check this sandbox where I show you the difference: CodeSandbox

Apple-pay with Stripe not recognized in Dashboard

I seem to have gotten backend index.js file working with an apple-pay payment request on the back-end. However the results do not show up in my Stripe dashboard. Spinning my wheels and cannot figure out why. Any help would be much appreciated.
Below is the code I am using on the back-end. When I press the pay button in Apple-Pay in the App, my terminal window shows "Payment requested" and "Success" messages.
I would then expect the USD amount to process in my stripe dashboard but I am gettin $0.00 and no activity. Any help would be wonderful!
// Add packages we need
const express = require('express')
const bodyParser = require('body-parser')
var stripe = require('stripe')('YOUR-SECRET-KEY')
// Create an express app
const app = express()
// Use body parser so we can parse the body of requests
app.use(bodyParser.json())
// Just a sanity check endpoint we can hit in the browser
app.get('/', function (req, res) {
res.send('This is the backend server for Metatoll Application!')
})
app.post('/pay', function (req, res) {
console.log('Payment requested')
var token = req.body.stripeToken
var amount = req.body.amount
var description = req.body.description
stripe.charges.create({
amount: amount,
currency: "usd",
description: description,
source: token,
}, function(err, charge) {
if (err !== null) {
console.log('error capturing')
console.log(err)
res.status(400).send('error')
} else {
console.log('success')
res.status(200).send('success')
}
});
})
app.listen(3000, () => {
console.log('Metatoll listening on port 3000')
})

Node.js app giving ERR_EMPTY_RESPONSE

I'm having serious issues with an app I am building with Node.js, Express, MongoDB and Mongoose. Last night everything seemed to work when I used nodemon server.js to `run the server. On the command line everything seems to be working but on the browser (in particular Chrome) I get the following error: No data received ERR_EMPTY_RESPONSE. I've tried other Node projects on my machine and they too are struggling to work. I did a npm update last night in order to update my modules because of another error I was getting from MongoDB/Mongoose { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND'}. I used the solution in this answer to try and fix it and it didn't work and I still get that error. Now I don't get any files at all being served to my browser. My code is below. Please help:
//grab express and Mongoose
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create an express app
var app = express();
app.use(express.static('/public/css', {"root": __dirname}));
//create a database
mongoose.connect('mongodb://localhost/__dirname');
//connect to the data store on the set up the database
var db = mongoose.connection;
//Create a model which connects to the schema and entries collection in the __dirname database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");
mongoose.connection.on("open", function() {
console.log("mongodb is connected!");
});
//start the server on the port 8080
app.listen(8080);
//The routes
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
//create an express route for the home page at http://localhost:8080/
app.get('/', function(req, res) {
res.send('ok');
res.sendFile('/views/index.html', {"root": __dirname + ''});
});
//Send a message to the console
console.log('The server has started');
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
These routes don't send anything back to the client via res. The bson error isn't a big deal - it's just telling you it can't use the C++ bson parser and instead is using the native JS one.
A fix could be:
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {
if (err) {
res.status(404).json({"error":"not found","err":err});
return;
}
res.json(data);
});
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
res.status(500).json({ error: "save failed", err: err});
return;
} else {
res.status(201).json(newMonth);
};
});
});
updated june 2020
ERR_EMPTY_RESPONSE express js
package.json
"cors": "^2.8.4",
"csurf": "^1.9.0",
"express": "^4.15.4",
this error show when you try to access with the wrong HTTP request. check first your request was correct
maybe your cors parameter wrong

Categories