我用Java编写了一个Web服务。并且ReactJS中的客户端调用我的Web服务并显示响应。我在localhost:8081上运行我的客户端,在localhost:8080上运行Tomcat Apache上的Web服务。但是当我运行我的客户端时,我收到一个错误(在下面发布)。请告诉我代码中的问题是什么?
View.jsx (客户端):
import React from 'react';
class View extends React.Component {
constructor() {
super();
this.state = {
text: "initial state"
};
}
componentDidMount() {
$.ajax({
url: "localhost:8080/UserManagement/rest/myService/data"
}).then((function(data) {
this.setState({text: data});
}).bind(this))
}
render() {
return (
<div>
{this.state.text}
</div>
);
}
}
export default View;
MyServer.java (网络服务):
package com.tutorialspoint;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.JSONObject;
@Path("myService")
public class MyServer {
@GET
@Path("/data")
@Consumes(MediaType.APPLICATION_JSON)
public Response queryRESTService(InputStream incomingData) {
JSONObject jsonObject = null;
try {
String output = "";
InputStream inputStream = new FileInputStream("C:\\Users\\username\\Desktop\\myJSON.txt");
InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
output += line + "\n";
}
jsonObject = new JSONObject(output);
bufferedReader.close();
}
catch (Exception e) {
}
return Response.status(200).entity(jsonObject.toString()).build();
}
@GET
@Path("/verify")
@Produces(MediaType.TEXT_PLAIN)
public Response verifyRESTService() {
String result = "MyRESTService Successfully started..";
return Response.status(200).entity(result).build();
}
}
答案 0 :(得分:2)
我猜你并不太了解CORS代表跨源资源共享。根据网络标准,不允许这样做。因此,您需要做的是在Java中设置CORS头以允许客户端发出请求。这将有助于:Using CORS headers with Java
答案 1 :(得分:1)
您没有在网址中指定任何协议。
在view.jsx文件中,将网址更改为&#34; http://localhost:8080/UserManagement/rest/myService/data&#34;。