使用来自localhost:8081的请求对象从NodeJs app.post调用localhost:8080 payara服务器不起作用

时间:2020-04-24 14:14:27

标签: node.js request localhost http-status-code-301 econnreset

后备服务器端口正在8080中运行 Node js在4000上运行 我正在使用app.post并使用request对象调用本地后端服务器。面临的问题。 以下代码不起作用:

 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”}

在邮递员中进行后端呼叫。

0 个答案:

没有答案
相关问题