-1

Here is my nodejs code that works perfectly with https site.

app.use(cors({ origin: '*' }));
app.use(express.json())
app.use("/user", userRouter);
app.use("/mention", mentionRouter);
app.use("/request", requestRouter);

But the problem is if I send the request from any HTTP site, I get an error saying TypeError: Failed to fetch and get no response. Here is my frontend code.

  const response = await fetch(WEB_URL + "mention", {
    method: "POST",
    body: JSON.stringify({
      to: users,
      text,
      link: window.location.toString(),
    }),
    headers: {
      "x-access-token": accessToken,
      "Content-Type": "application/json",
    },
  });

I tried answers from this Getting "TypeError: failed to fetch" when the request hasn't actually failed but not working.

JustABeginner
  • 785
  • 2
  • 11
  • 26

1 Answers1

-2

Sorry to be one of those people, but your variables are not defined in your snippet so I can't really see what you have defined. Example:

const response = await fetch(WEB_URL + "mention",

Nobody knows what WEB_URL means and it can be apart of the problem. Also, window.location can be used like http://example.com/, but it is an object so it could print "[object Object]". Instead, try using window.location.href. Your problem most likely is that the Fetch JS API is not available with HTTP sites for security reasons. There's not much more to the problem.

Parking Master
  • 551
  • 1
  • 4
  • 20
  • WEB_URL points to my localhost and window.location.toString() gives the current url I am on. They work fine for me. It is actually the error as mentioned on the question that is really rendering me speechless at the moment. Thanks for the comment. What's the security reason by the way? – JustABeginner Oct 27 '21 at 17:51
  • HTTP Means (HyperText Transfer Protocol) and HTTPs Means (HyperText Transfer Protocol secure). The reason is that HTTP is not secure when transferring data over internet, so browsers do not let insecure sites with **HTTP** use special APIs for security reasons. – Parking Master Oct 27 '21 at 17:56