1

支持的服务器端口在 8080 上运行节点 js 在 4000 上运行我正在使用 app.post 并使用请求对象来调用本地后端服务器。面临问题。以下代码不起作用:

 let express = require('express');
const cors = require('cors');
const request = require('request');


const app = express();
app.use(express.json());
app.use(cors());
app.options('*', cors());
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

app.all('/*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,POST');
    res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
    next();
});


app.post("/login", (req,res) => {
        let loginRequest = {
            username : req.body.username,
            password:  req.body.password,
        }
        request({
            url:  "http://localhost:8080/app/login", 
            method: "POST",
            rejectUnauthorized: false,
            json: true,
            body: loginRequest ,
            followOriginalHttpMethod : true,
            followAllRedirects : true,
            headers : {"Content-Type": "application/json" 
              },
        }, function (error, response, body){
            console.log("response in server " + JSON.stringify(response)  + " body " + JSON.stringify(body) + " error " + JSON.stringify(error));
            if (response != undefined && response.headers['authorization'] != undefined) {
              //do some logic 
            } else {
                console.log("Invalid credential!");
                res.sendStatus(401);
            }
        });
    });


const port = process.env.PORT || 4000;
    app.listen(port, () => {
        console.log(`Server running at http://localhost:${port}`);
    });

我也使用过:Cors 设置。

当我打印时,console.log 给出的结果为:服务器中的错误响应

{"errno":"ECONNRESET","code":"ECONNRESET","syscall":"read"}

在 postman 工作的后端调用。

4

0 回答 0