为何Stripe支付请求POST /process-payment返回404?端点已声明
问题
我有一个用于Stripe支付的Angular TypeScript组件,希望pay(...)方法的支付金额存入JSON REST API数据库(后续计划改用MongoDB)。但调用POST http://localhost:3000/process-payment时出现404 (Not Found)错误,尽管server.js中已声明该端点,请问可能的原因是什么?
Angular组件代码
pay(amount: any) { var handler = (<any>window).StripeCheckout.configure({ key: 'pk_test_51OKda9H5eXnyJcWfb1dh0tGzXv2FclyLrDzPCqL5SGsyuDmZr2ljbfquR7kMZaRVONanewECDPXfPWswAiKQvuxl009QOEIECu', locale: 'auto', token: (token: any) => { console.log(token.id); console.log(token); alert('Token Created!!'); // Attempt to reach the server endpoint this.http.post('http://localhost:3000/process-payment', { token, amount }) .subscribe((response: any) => { if (response.success) { console.log('Payment success!'); // Update client-side logic as needed } }); } }); }
server.js代码
// Express server with Stripe integration const express = require('express'); const bodyParser = require('body-parser'); const stripe = require('stripe')('my live stripe key'); const app = express(); app.use(bodyParser.json()); // Endpoint for processing payments app.post('/process-payment', async (req, res) => { const { token, amount } = req.body; try { // Create a payment intent or charge using Stripe API const paymentIntent = await stripe.paymentIntents.create({ amount: amount * 100, // Amount in cents currency: 'usd', // Change to your desired currency payment_method: token.id, confirmation_method: 'manual', confirm: true, }); // Update balance in your JSON REST API database const userId = req.user.id; // Replace this with your user identification logic const userBalance = await Balance.findOne({ userId }); if (userBalance) { userBalance.amount += amount; await userBalance.save(); } else { // Create a new balance entry if not exists await Balance.create({ userId, amount }); } res.json({ success: true, paymentIntent }); } catch (error) { } });
可能的原因及解决办法
Express服务未启动在指定端口:你的
server.js完全缺少端口监听代码,Express不会自动绑定3000端口。必须在文件末尾添加启动逻辑:app.listen(3000, () => { console.log('服务器运行在 http://localhost:3000'); });没有这段代码,服务根本没启动,请求自然会返回404。
服务器代码存在致命错误,导致服务启动失败:
- 你使用了
Balance模型但未引入对应的模块(比如const Balance = require('./models/Balance');,路径根据你的项目结构调整),启动时会抛出ReferenceError,服务无法正常运行。 - 空的
catch块会导致错误静默失败,一旦Stripe请求或数据库操作出错,服务器可能崩溃,端点无法访问。建议添加错误处理:catch (error) { console.error('支付处理失败:', error); res.status(500).json({ success: false, error: error.message }); }
- 你使用了
端口被占用或服务未正确启动:
- 检查3000端口是否被其他程序占用:Windows系统使用
netstat -ano | findstr :3000命令,Mac/Linux使用lsof -i :3000命令,必要时更换端口或杀掉占用进程。 - 启动服务器时查看终端输出,运行
node server.js后如果没有报错和启动日志,说明服务未正常启动。
- 检查3000端口是否被其他程序占用:Windows系统使用
请求路径或跨域配置冲突:
- 虽然路径写法正确,但如果Angular项目使用了代理配置(
proxy.conf.json),直接访问localhost:3000可能被代理拦截,不过这种情况通常返回跨域错误而非404,可以检查代理配置是否影响路径。
- 虽然路径写法正确,但如果Angular项目使用了代理配置(
内容的提问来源于stack exchange,提问作者kristixn
相关产品推荐
相关产品推荐

