简体   繁体   English

获取API。 我从我自己的快递服务器得到一个空字符串

[英]FetchAPI . Im getting an empty string from my own express server

I've set up an express.js server on 4000 port.我在 4000 端口上设置了一个 express.js 服务器。 getting a request and sending a plain text string.获取请求并发送纯文本字符串。

let express = require("express");
const app = express();
const port = 4000;

app.listen(port, () => { console.log(`SERVER is running on port ${port}`)});

app.use(express.text());

app.get("/", (req,res) =>{
   console.log("Get from /");
   res.send("Hello world");
});

and i'am trying to fetch a string "Hello world"using fetchApi.我正在尝试使用 fetchApi 获取字符串“Hello world”。

window.onload = ()=>{
  fetch("http://127.0.0.1:4000/", {
      method: "GET",
      mode: "no-cors"
  }).then(res=>{
      return res.text();
  }).then( text => {
      console.log(text);
  });
};

i am getting an empty string in console but when i open network sent requests i see the message in network response.我在控制台中收到一个空字符串,但是当我打开网络发送请求时,我在网络响应中看到了该消息。

You said:你说:

 mode: "no-cors"

Which means "I am not going to do anything that requires the server to grant permission with CORS so don't fill the console with errors if I don't have that permission".这意味着“我不会做任何需要服务器授予 CORS 权限的事情,因此如果我没有该权限,请不要在控制台中填充错误”。

Since reading a response cross-origin requires permission from CORS and you said you didn't want permission, you get an empty string back when you try to read the response.由于读的响应跨域需要从CORS许可,你说你不想许可,您当您尝试读取响应得到一个空字符串返回。

If you want to read the response, you need CORS, so take the mode config out.如果要读取响应,则需要 CORS,因此将mode配置取出。

If you are using the last version of Express so try this code and you don't need express.text():如果您使用的是 Express 的最新版本,请尝试使用此代码并且您不需要 express.text():

 const express = require("express");
 const app = express();
 const port = 4000;
 app.listen(port, () => { console.log(`SERVER is running on port ${port}`)}); 
 app.get("/", (req,res) =>{ console.log("Get from /"); res.send("Hello world") });

Then :然后 :

window.onload = ()=>{ fetch("http://127.0.0.1:4000/", { method: "GET"}).then(res=>{ return res }).then( text => { console.log(text); }); };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM