fix: chat widget route ordering and missing body parser

- Move GET /chat/widget.js before GET /chat/:shop to prevent Express
  matching 'widget.js' as the :shop param and returning JSON
- Move POST/GET /chat/:shop after body parser registration so req.body
  is populated when customers send messages

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
MOHAN 2026-06-12 20:50:42 +05:30
parent aef977eb99
commit a27d586c82

View File

@ -33,22 +33,7 @@ app.get('/free-access/:shop', (req, res) => {
});
// ── PUBLIC CHAT ENDPOINTS (for customer widget) ──────────────────────────────
app.post('/chat/:shop', (req, res) => {
const shop = decodeURIComponent(req.params.shop || '').toLowerCase().trim();
const { text, visitorId } = req.body;
if (!shop || !text) return res.status(400).json({ error: 'shop and text required' });
const msg = addChatMessage(shop, 'customer', String(text).slice(0, 1000), visitorId || null);
res.json({ ok: true, message: msg });
});
app.get('/chat/:shop', (req, res) => {
const shop = decodeURIComponent(req.params.shop || '').toLowerCase().trim();
if (!shop) return res.status(400).json({ error: 'shop required' });
const chat = readChat(shop);
res.json({ messages: chat.messages || [] });
});
// Embeddable widget script ─ <script src="https://backend.data4autos.com/chat/widget.js?shop=SHOP"></script>
// widget.js MUST be before /chat/:shop — otherwise Express treats "widget.js" as the :shop param
app.get('/chat/widget.js', (req, res) => {
const shop = (req.query.shop || '').toLowerCase().trim();
const backendUrl = 'https://backend.data4autos.com';
@ -205,7 +190,23 @@ app.use('/', auth);
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
// 4) Your other endpoints
// 4) Chat message endpoints (need body parser — must be after it)
app.post('/chat/:shop', (req, res) => {
const shop = decodeURIComponent(req.params.shop || '').toLowerCase().trim();
const { text, visitorId } = req.body;
if (!shop || !text) return res.status(400).json({ error: 'shop and text required' });
const msg = addChatMessage(shop, 'customer', String(text).slice(0, 1000), visitorId || null);
res.json({ ok: true, message: msg });
});
app.get('/chat/:shop', (req, res) => {
const shop = decodeURIComponent(req.params.shop || '').toLowerCase().trim();
if (!shop) return res.status(400).json({ error: 'shop required' });
const chat = readChat(shop);
res.json({ messages: chat.messages || [] });
});
// 5) Your other endpoints
app.post('/fulfillment', (req, res) => {
console.log('POST /fulfillment:', req.body);
res.sendStatus(200);