POST API在应用程序中使用时返回404(未找到),在使用CURL时正常工作。

huangapple go评论69阅读模式
英文:

POST API returning 404 (Not Found) when being used in app, works fine with CURL

问题

我有一个聊天应用程序,我正在开发,它使用MongoDB、Express API和Socket.io作为后端。当我尝试从应用程序内部向API发送数据时,它会返回404错误并且请求失败。但是当我使用CURL尝试发送数据时,它可以正常工作并且数据会保存在MongoDB中。

以下是我在server.js中创建API的代码:

// ...(前面的代码)

// API端点
app.use(express.json());

app.get('/api/conversations', async (req, res) => {
  try {
    const conversations = await Conversation.find().populate('messages');
    res.json(conversations);
  } catch (error) {
    console.error('获取会话时出错:', error);
    res.status(500).json({ error: '获取会话失败' });
  }
});

app.post('/api/conversations', async (req, res) => {
  const { recipients } = req.body;

  try {
    const conversation = new Conversation({
      recipients,
    });
    await conversation.save();
    res.status(201).json(conversation);
  } catch (error) {
    console.error('创建会话时出错:', error);
    res.status(500).json({ error: '创建会话失败' });
  }
});

app.post('/api/messages', async (req, res) => {
  const { conversationId, sender, text } = req.body;

  try {
    const message = new Message({ conversationId, sender, text });
    await message.save();
    res.status(201).json(message);
  } catch (error) {
    console.error('保存消息时出错:', error);
    res.status(500).json({ error: '保存消息失败' });
  }
});

前端/客户端代码:

useEffect(() => {
  fetchConversations();
}, []);

async function fetchConversations() {
  try {
    const response = await fetch('/api/conversations');
    if (!response.ok) {
      throw new Error('获取会话失败');
    }
    const data = await response.json();
    setConversations(data);
  } catch (error) {
    console.error('获取会话时出错:', error.message);
  }
}

function createConversation(recipients) {
  fetch('/api/conversations', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ recipients }),
  })
    .then((response) => {
      if (!response.ok) {
          throw new Error('创建会话失败');
      }
      return response.json();
    })
    .then((data) => {
      console.log('数据', data)
      setConversations((prevConversations) => [
        ...prevConversations,
        data,
      ]);
    })
    .catch((error) => {
      console.error('创建会话时出错:', error.message);
    });
}

会话模型:

const mongoose = require('mongoose');

const conversationSchema = new mongoose.Schema({
  recipients: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Friend',
    required: true
  }],
  messages: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Message'
  }]
});

const Conversation = mongoose.model('Conversation', conversationSchema);

module.exports = Conversation;

我已经尝试多次测试API,每次都能正常工作,除了在客户端应用程序中访问时。

英文:

I have a chat app that I'm working on that uses MongoDB, Express API and Socket.io for a backend. When I try to POST data to the API from within the app, it gives a 404 error and the request fails. But when I use CURL to try to POST data, it works and data is saved in MongoDB

Here's the server.js code where I create the API:

const express = require('express');
const http = require('http');
const mongoose = require('mongoose');

const app = express();
const server = http.createServer(app);
const io = require("socket.io")(server, {
    cors: {
        origin: "*",
    }
  });

const Conversation = require('./database/ConversationModel');
const Message = require('./database/MessageModel');

mongoose
  .connect('<connection_string>?retryWrites=true&w=majority', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log('Connected to MongoDB');
    server.listen(5173, () => {
      console.log('Server listening on port 5173');
    });
  })
  .catch((error) => {
    console.error('Failed to connect to MongoDB:', error);
  });

io.on('connection', (socket) => {
  const { id } = socket.handshake.query;

  socket.join(id);

  socket.on('send-message', async ({ recipients, text }) => {
    try {
      // Save the message to the database
      const message = new Message({
        conversationId: recipients.join('-'),
        sender: id,
        text,
      });
      await message.save();

      // Emit the message to all recipients' sockets
      recipients.forEach((recipient) => {
        const newRecipients = recipients.filter((r) => r !== recipient);
        newRecipients.push(id);
        socket.broadcast.to(recipient).emit('receive-message', {
          recipients: newRecipients,
          sender: id,
          text,
        });
      });
    } catch (error) {
      console.error('Error sending message:', error);
    }
  });
});

// API endpoints

app.use(express.json());

app.get('/api/conversations', async (req, res) => {
  try {
    const conversations = await Conversation.find().populate('messages');
    res.json(conversations);
  } catch (error) {
    console.error('Error fetching conversations:', error);
    res.status(500).json({ error: 'Failed to fetch conversations' });
  }
});

app.post('/api/conversations', async (req, res) => {
    const { recipients } = req.body;
  
    try {
      const conversation = new Conversation({
        recipients,
      });
      await conversation.save();
      res.status(201).json(conversation);
    } catch (error) {
      console.error('Error creating conversation:', error);
      res.status(500).json({ error: 'Failed to create conversation' });
    }
  });

app.post('/api/messages', async (req, res) => {
  const { conversationId, sender, text } = req.body;

  try {
    const message = new Message({ conversationId, sender, text });
    await message.save();
    res.status(201).json(message);
  } catch (error) {
    console.error('Error saving message:', error);
    res.status(500).json({ error: 'Failed to save message' });
  }
});

Front-end/client code:

useEffect(() => {

    fetchConversations();
  }, []);

  async function fetchConversations() {
    try {
      const response = await fetch('/api/conversations');
      if (!response.ok) {
        throw new Error('Failed to fetch conversations');
      }
      const data = await response.json();
      setConversations(data);
    } catch (error) {
      console.error('Error fetching conversations:', error.message);
    }
  }

  function createConversation(recipients) {
    fetch('/api/conversations', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ recipients }),
    })
      .then((response) => {
        if (!response.ok) {
            throw new Error('Failed to create conversation');
        }
        return response.json();
      })
      .then((data) => {
        console.log('data')
        setConversations((prevConversations) => [
          ...prevConversations,
          data,
        ]);
      })
      .catch((error) => {
        console.error('Error creating conversation:', error.message);
      });
  }

Conversation model:

const mongoose = require('mongoose');

const conversationSchema = new mongoose.Schema({
  recipients: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Friend',
    required: true
  }],
  messages: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Message'
  }]
});

const Conversation = mongoose.model('Conversation', conversationSchema);

module.exports = Conversation;

I've tried testing the API multiple times and it works every time apart from when accessed from the client app

答案1

得分: -1

事实证明,我只是没有意识到我必须在不同的端口上运行我的客户端和服务器。我知道它们必须分开运行,但我以为这只是意味着不同的进程,之前在不同的端口上运行时我曾遇到过错误。现在一切都正常运行。

英文:

It turns out I just didn't realise that I had to run my client and server on different ports. I knew they had to be ran separately but I thought that just meant different processes and I'd had errors previously with running on different ports. Everything works now

huangapple
  • 本文由 发表于 2023年6月29日 04:43:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定