http://localhost:3002(源)和http://localhost:8080/configurator(服务器)之间的本地测试时,我有CORS问题
因此,我决定在它们之间建立一个代理,该代理会将access-control-allow的origins头附加到服务器的任何响应中。我似乎反应良好,但并没有给我身体本身。忽略客户端代码,我只是尝试用邮递员(客户端软件)进行测试->代理(节点快递)和最终服务器(球衣)
我在邮递员中的请求发送到http://localhost:3001/file/(代理),并在下面发送设置为代理的应用程序/ json代码的JSON字符串内容类型标头,
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标头以进行响应。
后端的下一个添加的端点,尤其是正在使用的特定端点是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();
}
}
我的问题是我只返回了一个空字符串。香港专业教育学院附上两张图片,其中一张显示代理服务器中的控制台输出,说正文为空,而邮递员中的结果相似。伙计们,我在做什么错?
更新:因此,我的代理现在可以使用以下代码:
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));
}
)
});
至少看起来好。现在,当我使用邮递员时,将请求发送到localhost:8080 / configurator(后端)或localhost:3001 / file(代理)会返回相同的结果,但是当我使用客户端应用程序并进行ajax调用时,我仍然在输出中看到CORS问题,该怎么办?现在的问题是,我什至会在下面附上我的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);
这只是一个愚蠢的示例,我从粘贴the http-proxy docs的一些代码后就存在了,错误处理显然不足以在一开始就用于生产目的,但是它表明您可以轻松创建代理并修改响应(在这种情况下,我添加了标题,因为这是您的主要用例)。
[我只是在我的服务器上尝试过,并在其中传递了请求正文,然后通过auth,它传递了错误和成功的http响应,并始终添加foo
标头。