简体   繁体   English

为什么 fetch() 方法在我的反应应用程序中不起作用?

[英]Why the fetch() method is not working in my react app?

I'm following this tutorial .我正在关注本教程 I think the fetch() method in App.js is not getting called.我认为App.js中的fetch()方法没有被调用。

Here's App.js :这是App.js

import React, { useState } from "react";
import "./App.css";

function App() {
  const makeOrder = () => {
    fetch("/api/order", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: "Helllloooo!",
    }).then((response) => response.json());
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>Markee</h1>
        <button type="button" class="btn btn-primary" onClick={makeOrder}>
          Send
        </button>
      </header>
    </div>
  );
}

export default App;

Here's order.js :这是order.js

// pages/api/order.js
import sendSMS from "../../utils/twilio";

alert("happened");
const handler = async (request, response) => {
  switch (request.method) {
    case "POST":
      await sendSMS("xxxxxxxx", "Hooola!");
      alert("this happened");
      response.status(200).json({ message });
      break;
    default:
      response.status(405).end("This method is not allowed for this route.");
      alert("that happened");
  }
};

export default handler;

Here's twilio.js :这是twilio.js

import twilio from "twilio";

alert("happened adda");

const accountSid = "xxxxxxxxxx";
const authToken = "xxxxxxxxxx";
const client = require("twilio")(accountSid, authToken);

const sendSMS = async (recipient, message) => {
  return await client.messages
    .create({
      mediaUrl: [
        "https://images.unsplash.com/photo-1545093149-618ce3bcf49d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=668&q=80",
      ],
      from: "whatsapp:xxxxxxx",
      to: recipient,
      body: message,
    })
    .then((message) => console.log(message.sid));
};

export default twilio;

This is my first time writing a react app on my own.这是我第一次自己编写 React 应用程序。 Thanks for your help!谢谢你的帮助!

Try with makeOrder(),尝试使用 makeOrder(),

import React, { useState } from "react";
import "./App.css";

function App() {
  const makeOrder = () => {
   alert("fetch called")
    return fetch("/api/order", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: "Helllloooo!",
    }).then((response) => response.json());
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>Markee</h1>
        <button type="button" class="btn btn-primary" onClick= 
    {()=>makeOrder()}>
          Send
        </button>
      </header>
    </div>
  );
}

export default App;

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

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