Reputation: 758
I have a Vue app on the frontend and a seperate express server with only a few routes. In app.js, I registered my routes as follows:
const express = require('express')
const cors = require('cors')
require('dotenv').config()
const orders = require('./routes/orders')
const webhooks = require('./routes/webhooks')
const app = express()
// http://expressjs.com/en/4x/api.html#express.urlencoded
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
// Register api routes
app.use('/', orders)
app.use('/create-payment-intent', orders)
app.use('/admin', orders)
app.use('/admin/:id', orders)
app.use('/webhook', webhooks)
/*
TODO - fall through route handler
*/
In /routes/orders.js
const express = require('express')
const router = express.Router()
const { flattenObject, orderValidationRules, validate } =
require('../middlewares/validations')
const OrdersController = require('../controllers/ordersController')
router.route('/').post(
orderValidationRules(),
validate,
OrdersController.apiPostOrder
)
router.route('/admin').get(OrdersController.apiGetOrders)
router.route('/create-payment-intent').post(OrdersController.apiCreatePaymentIntent)
router.route('/:id').delete(OrdersController.apiDeleteOrder)
module.exports = router
/routes/webhooks
const express = require('express')
const router = express.Router()
const WebhooksController = require('../controllers/webhooksController')
router.route('/webhook').post(express.raw({type: 'application/json'}),
WebhooksController.apiPostWebhookEvent)
module.exports = router
On the frontend, I can post my orders, hit admin route, the create-payment-intent route on the server is reached and responds 200, yet when I see if the webhook was reached on the stripe dashboard says pending and on the server 404 not found:
[![enter image description here][1]][1]
This is an express routing issue and I am uncertain if I in fact set my routes properly. How do I fix this? Also on the localhost port for the server I get cannot get for /create-payment-intent and for /webhook, /admin is fine. [1]: https://i.sstatic.net/qoojq.png
Upvotes: 0
Views: 320
Reputation: 1
Your problem is that in your app.js you placed a middleware function that parses incoming requests with JSON
app.use(express.json())
and then in your route /routes/webhooks you pass another middleware express.raw({type: 'application/json'}
to work you put the following in your app.js
// Use JSON parser for all non-webhook routes
app.use(
(
req: express.Request,
res: express.Response,
next: express.NextFunction
): void => {
if (req.originalUrl === '/webhook/') {
next();
} else {
express.json())(req, res, next);
}
}
);
Upvotes: 0