I created a server using Express, Sequelize and mySql. The below code is my route for product:
const express = require('express');
const Product = require('../models/product');
const router = express.Router();
router.get("/", async (req, res) => {
/* const products = await Product.findAll();
if (product) {
res.status(200).send({message: 'Product found successfully', data: products})
} else {
res.status(404).send({message: 'Product not found'})
} */
res.status(200).end()
});
router.post("/", async (req, res) => {
try {
const product = await Product.create(req.body);
res.send(product)
} catch (error) {
console.log(error);
}
})
module.exports = router;
This is my server.js code:
const express = require("express");
const app = express();
require("dotenv").config();
const cors = require("cors");
const endpoints = require("express-list-endpoints");
const port = 5555;
const productRouter = require("./src/routes/product");
/* const variantRouter = require("./src/routes/variant"); */
const sequelize = require("./src/db/config");
app.use(express.static(__dirname "/public"));
var corsOption = {
origin: true,
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true,
exposedHeaders: ["x-auth-token"],
};
app.use(express.json());
app.use(cors(corsOption))
app.use("products", productRouter);
/* app.use("variant", variantRouter); */
app.get("/", (req, res) => {
res.send("Server is Healthy!");
});
sequelize.sync({ force: true }).then(() => {
console.log("Drop and re-sync db.");
});
console.log(endpoints(app));
app.listen(process.env.PORT, () => {
console.log(`server is listening at http://localhost:${process.env.PORT}`),
sequelize.authenticate().then(
() => console.log("DB Connected"),
(err) => console.log("Error in connection", err)
);
});
I also have my model here:
const sequelize = require("../db/config");
const Sequelize = require("sequelize");
const Variant = require("./variants")
const Product = sequelize.define("products", {
id: {
type: Sequelize.UUID,
primaryKey: true,
},
product_name: {
type: Sequelize.STRING,
allowNull: false,
},
product_description: {
type: Sequelize.STRING,
allowNull: false,
},
date_uploaded: {
type: Sequelize.DATE,
allowNull: true
},
date_edited: {
type: Sequelize.DATE,
allowNull: true,
},
product_varieties: {
type : Sequelize.UUID,
reference: {
model: 'variant',
key: 'id'
}
},
},
{timestamp: false}
);
module.exports = Product;
The route in my server JS is working showing the String sent. But the route from product.js is not working. Telling me can't GET and can't POST on /products
What is the solution to this?
CodePudding user response:
You forgot the /
before products
in app.use("/products")
CodePudding user response:
Looks like your static public folder has conflicted with the API router, try putting every API router before the app.use(express.static(__dirname "/public"));
I found the solution here: Express serving static files and routing