繁体   English   中英

Node Express 代理获取状态代码:404 Not Found 而不是 200 成功代码

[英]Node Express proxy getting Status Code: 404 Not Found instead of 200 success code

我的 server.js 文件如下所示:

const express = require('express');
const http = require('http');
const path = require('path');
//const request = require('request');
const app = express();
var cors = require('cors')
app.use(cors())

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("access-control-allow-credentials", "true"),
        // res.header("access-control-allow-methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"), 
        res.header("access-control-allow-methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"),

        next();
});

var corsOptions = {
    origin: 'http://localhost:8080',
    optionsSuccessStatus: 200
}

const port = process.env.PORT || 3001;

app.use(express.static(__dirname + '/dist/myApp'));

app.get("/*", (req, res) => res.sendFile(path.join(__dirname)));

app.post("/dashboard", cors(corsOptions), function(req, res) {
    console.log(req.headers); // the posted data
    console.log(req.query.module);
    res.sendStatus(200)
});

const server = http.createServer(app);

server.listen(port, () => console.log('Running......'));

当我执行 node server.js 并在浏览器中点击http://localhost:3001/时,我得到了我在同一个文件中提到的 /dashboard 的页面。

但我收到状态代码:404 Not Found。 网络选项卡中显示的 URL 是http://localhost:3001/student/allstudent

我还应该改变什么? 如果以 4200 端口的 proxy.conf.json 开头,它将正常工作。 但现在我不是作为 proxy.conf.json 开始的,因为我正在开始节点 server.js。 可以帮我一些忙吗? 我们是否应该为 express 提供任何代理与角度节点服务器不同。

💡 这是我的文件夹结构示例:

/**
 * dist
 *   - myApp
 *     - index.html
 * src
 *   index.js
 * package.json
 */

在我的index.js我使用了上面的代码,但在你的app.get('/*')我使用下面的代码进行了更改 👇:

app.get("/*", (req, res) => res.sendFile(path.join(__dirname, '../dist/myApp', 'index.html')));

使用上面的代码👆,它工作正常。

更新:为什么会出现错误?

💡发送POST请求时出现404 错误的原因是因为您的 express 服务器中没有任何POST方法。

👨🏻‍🏫 因此,例如,您可以添加与上述相同的路由,并且不要忘记将方法从GET更改为POST

POST方法相同的 Route 示例

app.post("/*", (req, res) => res.sendFile(path.join(__dirname, '../dist/myApp', 'index.html')));

因此,现在您有 1 个与 2 个方法相同的路由,即GETPOST ,如下面的代码:

// route with GET METHOD
app.get("/*", (req, res) => res.sendFile(path.join(__dirname, '../dist/myApp', 'index.html')));
// route with POST METHOD
app.post("/*", (req, res) => res.sendFile(path.join(__dirname, '../dist/myApp', 'index.html')));

现在,您可以再试一次,如果它适用于POST方法并且您不需要GET方法,那么您可以使用GET方法删除那些。

我希望它可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM