简体   繁体   English

GraphQL + React-> Express PROXY(网关)中间件

[英]GraphQL + React -> Express PROXY(Gateway) Middleware

So I've been trying to use GraphQL, React and Express(CORS issues) together. 所以我一直在尝试同时使用GraphQL,React和Express(CORS问题)。 I have an API in another URL. 我在另一个URL中有一个API。 So basically what I want to do is; 所以基本上我想做的是

  • I will send API request to Express, 我将API请求发送给Express,
  • Express should redirect my GraphQL Query to the API Address. Express应该将我的GraphQL查询重定向到API地址。

First one is okay, right now I am sending API requests to Express. 第一个还可以,现在我正在向Express发送API请求。 But it isn't sending my GraphQL URL to another URL. 但是它没有将我的GraphQL URL发送到另一个URL。

This is my code so far; 到目前为止,这是我的代码;

 app.use('/api', function (req, res) {
  res.header("Access-Control-Allow-Origin", "http://localhost:8081");
  // restrict it to the required domain
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
  // Set custom headers for CORS
  res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Custom-Header");
  if (req.method == "OPTIONS") {
    res.status(200);
    res.send();
  } else {
    const response = fetch('http://sssss.elasticbeanstalk.com/graphql', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: req,
    }).then(resp =>  res.send(CircularJSON.stringify(req)))
      .catch(error => res.send(error));
  }

Do I have to create a GraphQL server in Express too? 我也必须在Express中创建GraphQL服务器吗?

you can use something like this method for fetching in express 您可以使用类似这种方法的快递方式

app.get('/api', (req , res ) =>{
      let user = {
        userData: req.body,
    }
    res.send(JSON.stringify(user));
    console.log(user.username)

    })

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

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