在 ember js 中使用 response.json() 从 API 获取响应时显示错误
Showing error while using response.json() in ember js to fetch response from API
我必须创建一个 Web 应用程序以在 mySQL 数据库中添加用户并使用 ember js 实现 UI。
app/components/user.hbs
<h1>User Management!</h1>
<div>
<label1>User Id </label1> <colon1>:</colon1>
<input1>{{input type="text" value=id placeholder="Enter id"}}</input1>
<label2>Firstname</label2> <colon2>:</colon2>
<input2>{{input type="text" value=firstname placeholder="Enter firstname"}}</input2>
<label3>Lastname</label3> <colon3>:</colon3>
<input3>{{input type="text" value=lastname placeholder="Enter lastname"}}</input3>
<label4>Mail Id</label4> <colon4>:</colon4>
<input4>{{input type="text" value=mailid placeholder="Enter mailid"}}</input4>
</div>
<button1 {{on "click" (fn this.user "add" id firstname lastname mailid )}}>Add User</button1>
<button2 {{on "click" (fn this.user "delete" id firstname lastname mailid )}}>Delete User</button2>
app/components/user.js
import Component from '@glimmer/component';
import {action} from "@ember/object";
import {tracked} from "@glimmer/tracking";
export default class UserComponent extends Component {
@action
async user (type,id,firstname,lastname,mailid){
let response=await fetch("http://localhost:8080/UserManagement/UserManagementServlet",
{ method: "POST",
mode:"no-cors",
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({
"type": type,
"id": id,
"firstname":firstname,
"lastname":lastname,
"mailid":mailid
})
});
let parsed=await response.json();
alert(parsed.status);
}
}
Servlet API 代码
//Required Header files
@WebServlet("/UserManagementServlet")
public class UserManagementServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException
{ res.setContentType("application/json");
res.setCharacterEncoding("UTF-8");
Gson gson=new Gson();
BufferedReader br=new BufferedReader(new InputStreamReader(req.getInputStream()));
String param=br.readLine();
User user = gson.fromJson(param, User.class);
HashMap<String,String> jsonfile=new HashMap<String,String>();
PrintWriter out=res.getWriter();
String url="jdbc:mysql://localhost:3306/employee",username="root";
String password="root";
Connection con=null;
PreparedStatement pst;
String query="select*from user";
ResultSet rs;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url,username, password);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Entered");
if (user.getType().equals("add")) {
try {
String insertquery="INSERT INTO user" +" (id,firstname,lastname, mailid) VALUES " +" (?,?, ?, ?);";
pst = con.prepareStatement(insertquery);
pst.setString(1, String.valueOf(user.getId()));
pst.setString(2, user.getFirstName());
pst.setString(3, user.getLastName());
pst.setString(4, user.getMailid());
jsonfile.put("id", String.valueOf(user.getId()));
jsonfile.put("firstname", user.getFirstName());
jsonfile.put("lastname", user.getLastName());
jsonfile.put("mailid", user.getMailid());
jsonfile.put("status","User Added Successfully");
String final1=gson.toJson(jsonfile);
System.out.println(final1);
out.println(final1);
pst.executeUpdate();
} catch (Exception e) {
out.println("error"+e);
}
}
out.flush();
}
}
它显示了 Cors 错误,所以我在 user.js 中添加了 "mode":"no-cors" 但之后 cors 错误消失了,但这个错误没有。
单击“添加用户”按钮时,此行显示错误“let parsed=await response.json();”
user.js:54 Uncaught (in promise) SyntaxError: Unexpected end of input
at UserComponent.user (user.js:54)"
基本上我只能推荐了解什么是CORS。简而言之,您正在尝试发出跨源请求(可能从 http://localhost:4200
到 http://localhost:8080
),然后您 必须 使用 CORS,否则浏览器将出于安全原因阻止此操作。
然而,这可能不是您想要的。出现此问题是因为您 运行 ember 开发服务器因此与您的后端有不同的来源。然而,在以后的生产中,这种情况不会发生——你不会 运行 那里的 ember 服务器,但可能有一个网络服务器同时为你的后端和前端服务。
对于这种情况(这 并不总是 但经常如此) ember 开发服务器具有 --proxy
选项。所以你会 运行 ember serve --proxy=http://localhost:8080
然后它将代理从 http://localhost:4200
到 http://localhost:8080
.
的所有 AJAX 请求
然后你把URL你fetch
从"http://localhost:8080/UserManagement/UserManagementServlet"
改成"/UserManagement/UserManagementServlet"
。
这是因为如果您不指定原点但以 /
开头,则它始终是 current 原点。这还有一个好处,即您不必为生产更改它。
然后浏览器将请求 "http://localhost:4200/UserManagement/UserManagementServlet"
,这将在没有 CORS 的情况下工作(也不需要 mode:"no-cors"
)并且 ember 开发服务器将重定向它。
但是如果您计划在生产中为后端和前端使用单独的服务器,这将无法工作,您将需要使用 CORS。
关于 mode:"no-cors"
的简短说明。这将总是 阻止您读取响应,从而使请求无法用于加载数据。这仅与 发送 数据相关。见 here:
JavaScript may not access any properties of the resulting Response.
我必须创建一个 Web 应用程序以在 mySQL 数据库中添加用户并使用 ember js 实现 UI。
app/components/user.hbs
<h1>User Management!</h1>
<div>
<label1>User Id </label1> <colon1>:</colon1>
<input1>{{input type="text" value=id placeholder="Enter id"}}</input1>
<label2>Firstname</label2> <colon2>:</colon2>
<input2>{{input type="text" value=firstname placeholder="Enter firstname"}}</input2>
<label3>Lastname</label3> <colon3>:</colon3>
<input3>{{input type="text" value=lastname placeholder="Enter lastname"}}</input3>
<label4>Mail Id</label4> <colon4>:</colon4>
<input4>{{input type="text" value=mailid placeholder="Enter mailid"}}</input4>
</div>
<button1 {{on "click" (fn this.user "add" id firstname lastname mailid )}}>Add User</button1>
<button2 {{on "click" (fn this.user "delete" id firstname lastname mailid )}}>Delete User</button2>
app/components/user.js
import Component from '@glimmer/component';
import {action} from "@ember/object";
import {tracked} from "@glimmer/tracking";
export default class UserComponent extends Component {
@action
async user (type,id,firstname,lastname,mailid){
let response=await fetch("http://localhost:8080/UserManagement/UserManagementServlet",
{ method: "POST",
mode:"no-cors",
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({
"type": type,
"id": id,
"firstname":firstname,
"lastname":lastname,
"mailid":mailid
})
});
let parsed=await response.json();
alert(parsed.status);
}
}
Servlet API 代码
//Required Header files
@WebServlet("/UserManagementServlet")
public class UserManagementServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException
{ res.setContentType("application/json");
res.setCharacterEncoding("UTF-8");
Gson gson=new Gson();
BufferedReader br=new BufferedReader(new InputStreamReader(req.getInputStream()));
String param=br.readLine();
User user = gson.fromJson(param, User.class);
HashMap<String,String> jsonfile=new HashMap<String,String>();
PrintWriter out=res.getWriter();
String url="jdbc:mysql://localhost:3306/employee",username="root";
String password="root";
Connection con=null;
PreparedStatement pst;
String query="select*from user";
ResultSet rs;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url,username, password);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Entered");
if (user.getType().equals("add")) {
try {
String insertquery="INSERT INTO user" +" (id,firstname,lastname, mailid) VALUES " +" (?,?, ?, ?);";
pst = con.prepareStatement(insertquery);
pst.setString(1, String.valueOf(user.getId()));
pst.setString(2, user.getFirstName());
pst.setString(3, user.getLastName());
pst.setString(4, user.getMailid());
jsonfile.put("id", String.valueOf(user.getId()));
jsonfile.put("firstname", user.getFirstName());
jsonfile.put("lastname", user.getLastName());
jsonfile.put("mailid", user.getMailid());
jsonfile.put("status","User Added Successfully");
String final1=gson.toJson(jsonfile);
System.out.println(final1);
out.println(final1);
pst.executeUpdate();
} catch (Exception e) {
out.println("error"+e);
}
}
out.flush();
}
}
它显示了 Cors 错误,所以我在 user.js 中添加了 "mode":"no-cors" 但之后 cors 错误消失了,但这个错误没有。
单击“添加用户”按钮时,此行显示错误“let parsed=await response.json();”
user.js:54 Uncaught (in promise) SyntaxError: Unexpected end of input
at UserComponent.user (user.js:54)"
基本上我只能推荐了解什么是CORS。简而言之,您正在尝试发出跨源请求(可能从 http://localhost:4200
到 http://localhost:8080
),然后您 必须 使用 CORS,否则浏览器将出于安全原因阻止此操作。
然而,这可能不是您想要的。出现此问题是因为您 运行 ember 开发服务器因此与您的后端有不同的来源。然而,在以后的生产中,这种情况不会发生——你不会 运行 那里的 ember 服务器,但可能有一个网络服务器同时为你的后端和前端服务。
对于这种情况(这 并不总是 但经常如此) ember 开发服务器具有 --proxy
选项。所以你会 运行 ember serve --proxy=http://localhost:8080
然后它将代理从 http://localhost:4200
到 http://localhost:8080
.
然后你把URL你fetch
从"http://localhost:8080/UserManagement/UserManagementServlet"
改成"/UserManagement/UserManagementServlet"
。
这是因为如果您不指定原点但以 /
开头,则它始终是 current 原点。这还有一个好处,即您不必为生产更改它。
然后浏览器将请求 "http://localhost:4200/UserManagement/UserManagementServlet"
,这将在没有 CORS 的情况下工作(也不需要 mode:"no-cors"
)并且 ember 开发服务器将重定向它。
但是如果您计划在生产中为后端和前端使用单独的服务器,这将无法工作,您将需要使用 CORS。
关于 mode:"no-cors"
的简短说明。这将总是 阻止您读取响应,从而使请求无法用于加载数据。这仅与 发送 数据相关。见 here:
JavaScript may not access any properties of the resulting Response.