簡體   English   中英

為處理 CORS 問題而構建的代理存在問題

[英]Problem with Proxy built to handle CORS issue

http://localhost:3002 (原點)和http://localhost:8080/configurator (服務器)之間進行本地測試時,我遇到了 CORS 問題

所以我決定在它們之間建立一個代理,它將 append 訪問控制允許起源 header 到服務器的任何響應。 我似乎得到了一個好的回應,但並沒有給我身體本身。 忽略客戶端代碼,我只是想用 postman(客戶端軟件)-> 代理(節點快遞)和終端服務器(球衣)進行測試

My request in postman sends to http://localhost:3001/file/ (the proxy) and sends a JSON string content type header set to application/json code for proxy is below

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
const request = require('request');
var logger = require('morgan');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.post('/file', (req, res) => {
  request.post(
    { url: 'http://localhost:8080/configurator' },
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }

      //console.log("body is"+body)
      //return res.json(body)//res.send(body)
       return res.send(body)
      //return res.send(JSON.parse(body));
      //return res.json(JSON.parse(body));
    }
  )
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

const PORT = 3001;
app.listen(PORT, () => console.log(`listening on ${PORT}`));

module.exports = app;

代理將請求轉發到我的后端並附加 CORS header 以響應。

接下來我添加了后端的端點,特別是正在使用的端點是 POST,它只是獲取一個 JSON 字符串然后嘗試返回它。

package ie.sidero.resources;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/configurator")
public class ConfiguratorFileResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getJsonConfigurationFile(){
        return "File/JSON will get returned here";
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public String addJsonConfigurationFile(String jsonConfiguration){
        return jsonConfiguration;
        //return Response.ok("Got the JSON it is: " + jsonConfiguration).header("Access-Control-Allow-Origin", "*").build();
        //return Response.status(Response.Status.OK).entity(jsonConfiguration).build();
    }
}

我的問題是我只返回一個空字符串。 我附上了兩張圖片,一張在代理中顯示控制台 output 說主體是空的,在 postman 中顯示類似的結果。 我在這里做錯了什么? 郵差 安慰

更新:所以我的代理現在可以使用以下代碼:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  req.header('Content-Type', 'application/json');
  next();
});

app.post('/file', (req, res) => {
  request.post(
    { url: 'http://localhost:8080/configurator',
      body: JSON.stringify(req.body)},
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }

       //var r = JSON.parse(body);
       //console.log("response body after send is: " +r)

       return res.json(JSON.parse(body));

    }
  )
});

好吧,至少看起來如此。 Sending requests to localhost:8080/configurator (backend) or localhost:3001/file (proxy) now returns same result when i use postman however im still seeing CORS issue in output when i use my client application and make ajax call, what could the現在的問題是,我什至用 ajax 調用我的代理,我附在下面,任何幫助都會很棒。 有什么問題就問小伙伴。

$.ajax({
            url: "http://localhost:3001/file", // Url to which the request is send
            type: "POST",             // Type of request to be send, called as method
            data: configJsonEdited,
            contentType: 'application/json',
            dataType: "json",         //Data expected back
            success: function(data)   // A function to be called if request succeeds
            {
                alert("YAY!!!!")
            },
            error: function(xhr, textStatus, errorThrown)
            {
                alert("Damnit!!")
                alert(textStatus);
                alert(errorThrown.toString());
            }
        });

最好不要從頭開始編寫代理。 如果你真的想要一個 nodejs 代理,你可以使用類似這樣的 http-proxy

const http = require('http');
const httpProxy = require('http-proxy');

const proxy = httpProxy.createProxyServer();

const server = http.createServer(function(req, res) {
    proxy.web(req, res, { target: 'http://localhost:8080' });
});

proxy.on('proxyRes', function (proxyRes, req, res) {
    res.setHeader('foo', 'bar');
}).on('error', function (e) {
    console.error(e);
});

server.listen(3001);

這只是一個愚蠢的例子,我從http-proxy 文檔中粘貼了一些代碼,錯誤處理顯然不足以用於生產目的,但它表明您可以輕松創建代理並修改響應(在這種情況下,我添加了 header,因為這是您的主要用例)。

我剛剛對我的服務器進行了嘗試,它傳入了請求正文,然后進行了身份驗證,它傳回了錯誤和成功 http 響應,並始終添加foo header。

通過將此依賴項添加到我的代理解決了 CORS 問題:

https://expressjs.com/en/resources/middleware/cors.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM