You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用API时出现Error 406及CORS错误求助

Troubleshooting 406 Error and CORS Issues in cPanel-Deployed Express App

Fix CORS Issues First

CORS errors stem from browser security policies blocking unapproved cross-origin requests. Resolve them with these steps:

  • Install and configure the cors middleware explicitly:
    const cors = require('cors');
    // Replace with your actual front-end domain (include http/https)
    const allowedOrigin = 'https://your-react-app-domain.com';
    
    const corsOptions = {
      origin: allowedOrigin,
      credentials: true, // Enable if your app uses auth tokens or cookies
      allowedHeaders: ['Content-Type', 'Authorization'],
      methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
    };
    
    app.use(cors(corsOptions));
    // Explicitly handle preflight OPTIONS requests required by browsers
    app.options('*', cors(corsOptions));
    
  • Avoid using app.use(cors()) with no configuration in production—it’s insecure and may still trigger strict browser checks.

Resolve 406 Not Acceptable Error

A 406 error means the server can’t return a response format the client expects. Fix this with these checks:

  • Ensure API routes send valid JSON responses using res.json(), which automatically sets the correct Content-Type: application/json header:
    app.get('/api/clients', async (req, res) => {
      try {
        const clients = await db.query('SELECT * FROM clients');
        res.json(clients); // Sends properly formatted JSON
      } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to fetch clients' });
      }
    });
    
  • Verify client request headers:
    • In Insomnia, set the Accept header to application/json (default for JSON requests).
    • In React, include the correct headers in fetch or axios calls:
      // Example with fetch
      fetch('https://your-backend-domain.com/api/orders', {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
      });
      
  • Add try/catch blocks to all async routes to catch silent errors (like database connection failures) that prevent valid responses from being sent.

cPanel Deployment-Specific Checks

  • Use the port assigned by cPanel instead of hardcoding a port (e.g., 3000):
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
    
  • Confirm your .htaccess file has valid rewrite rules to forward requests to the Node.js server. A typical cPanel Node.js .htaccess looks like:
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ http://localhost:XXXX/$1 [P,L]
    
    Replace XXXX with the port listed in your cPanel Node.js app settings.
  • Ensure the entry point in cPanel’s Node.js configuration points directly to your server.js file.

Debugging Tips

  • Enable request logging in Express to inspect incoming headers and requests:
    app.use((req, res, next) => {
      console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
      console.log('Request Headers:', req.headers);
      next();
    });
    
  • Check cPanel’s Node.js app error logs (found in the Node.js GUI under "Errors") for server-side issues you might miss.
  • Test API routes directly via curl to rule out client-side problems:
    curl -H "Accept: application/json" https://your-backend-domain.com/api/orders
    

内容的提问来源于stack exchange,提问作者markcfleming

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:35:32