我已經使用Java編寫了Web服務。 ReactJS中的客戶端調用我的Web服務並顯示響應。我在本地主機:8081上運行我的客戶端,並在localhost:8080上運行Tomcat Apache上的Web服務。但是當我運行我的客戶端時,我收到一個錯誤(發佈在下面)。請告訴我的代碼中可能存在什麼問題?ReactJS客戶端無法與Java 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();
}
}
https://enable-cors.org/ –