简体   繁体   English

如何在Node.js中使用数据和标头重定向到另一个Web服务

[英]How to redirect to another web service with data and header in nodejs

I am creating rest web service using express nodejs framework. 我正在使用Express Node.js框架创建其余Web服务。 I want to navigate to second.js page from first.js and need to send data and header to it. 我想从first.js导航到second.js页面,并需要向其发送数据和标头。

first.js first.js

const express = require("express");
const http = require("http");

var router = express.Router();

var options = {
  host: "localhost",
  port: "3000",
  path: "/second",
  method: "POST"
};

router.get("/", function(req, res, next) {
  http.request(options);
});

module.exports = router;

second.js second.js

var express = require("express");
var router = express.Router();

router.get("/", function(req, res, next) {
  res.send("Hello");
});

module.exports = router;

app.js app.js

app.use("/first", first);
app.use("/second", second);

I tried like above but it doesn't navigate to second.js web service. 我如上所述尝试过,但是它无法导航到second.js Web服务。 Does anyone know what I am doing wrong ? 有人知道我在做什么错吗?

Your code is not performing a redirection. 您的代码未执行重定向。 You are actually making a call from within the first endpoint to a second endpoint and acting more like a proxy. 您实际上是在从第一个端点到第二个端点进行呼叫,并且其行为更像是代理。

A redirection is performed by calling res.redirect as defined in the express documentation at http://expressjs.com/en/api.html (Search for res.redirect). 通过调用http://expressjs.com/en/api.html的快速文档中定义的res.redirect来执行重定向(搜索res.redirect)。 A redirection returns a HTTP redirect response that the users browser will follow to a new URL. 重定向返回HTTP重定向响应,用户浏览器将跟随该URL到新URL。 Unfortunately, redirections do not allow headers to be passed and it will be executed as a GET call(This is what redirections are designed for.). 不幸的是,重定向不允许传递标头,它将作为GET调用执行(这是重定向的目的。)。 You can include whatever query params you want in the URL though and set cookies (refer to How to forward headers on HTTP redirect ) 您可以在URL中包含所需的任何查询参数,并设置cookie(请参阅如何在HTTP重定向上转发标头

I think you are using POST in your request 我认为您在请求中使用了POST

But only set up GET on your second endpoint 但是只在第二个端点上设置GET

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

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