繁体   English   中英

为什么我的网站在我的电脑上运行良好,而在其他电脑上却不行?

[英]Why is my website running fine on my computer but not on other's?

我制作了一个 Spotify web 应用程序并使用 Netlify 启动它。 当我运行它的服务器文件时,它在我的计算机上运行良好,但在我朋友的计算机上运行良好。 起初我以为是因为 Spotify API,但我制作的另一个 web 应用程序不使用任何 API,也只能在我的计算机上运行。 我认为这是因为服务器端口或其他原因,但我不知道如何修复它。 这是网站 url 和服务器端代码。

https://xenodochial-kepler-118793.netlify.app

服务器.js

const express = require("express");
const SpotifyWebApi = require("spotify-web-api-node");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const port = 4000 || process.env.PORT;

require("dotenv").config();

app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));

// Create the api object with the credentials
var spotifyApi = new SpotifyWebApi({
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET,
});

// Retrieve an access token.
function newToken() {
  spotifyApi.clientCredentialsGrant().then(
    function (data) {
      console.log("The access token expires in " + data.body["expires_in"]);

      // Save the access token so that it's used in future calls
      spotifyApi.setAccessToken(data.body["access_token"]);
    },
    function (err) {
      console.log("Something went wrong when retrieving an access token", err);
    }
  );
}

newToken();

tokenRefreshInterval = setInterval(newToken, 1000 * 60 * 60);

app.post("/search_result", (req, res) => {
  spotifyApi
    .searchArtists(req.body.keyword)
    .then(function (data) {
      let search_res = data.body.artists.items;
      res.json(search_res);
      res.end();
    })
    .catch((err) => {
      console.log(err);
      res.status(500).send(err);
    });
});

app.get("/albums/:id", (req, res) => {
  console.log(req.params.id);
  spotifyApi
    .getArtistAlbums(req.params.id, { limit: 40 })
    .then(function (data) {
      res.json(data.body.items);
      res.end();
    });
});

app.get("/albums/tracks/:albumID", (req, res) => {
  console.log(req.params.albumID);
  spotifyApi
    .getAlbumTracks(req.params.albumID, { limit: 20 })
    .then(function (data) {
      console.log(data.body);
      res.json(data.body.items);
      res.end();
    });
});

app.listen(port, () => console.log(`It's running on port ${port}`));

主.js

import React, { Component } from "react";
import SingerBox from "./SingerBox";
import axios from "axios";
import "../../App.css";

export class Main extends Component {
  constructor(props) {
    super(props);
    this.state = {
      keyword: "",
      artists: [],
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({ keyword: e.target.value });
  }

  handleSubmit(e) {
    e.preventDefault();
    if (this.state.keyword === "") {
      alert("Enter Search Keyword");
    }
    axios
      .post(
        "/search_result",
        {
          keyword: this.state.keyword,
        },
        {
          headers: {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
          },
        }
      )
      .then((res) => {
        this.setState({ artists: res.data });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  render() {
    return (
      <div className="container">
        <div className="main">
          <form onSubmit={this.handleSubmit}>
            <label className="header" htmlFor="search">
              Explore New Artists
            </label>
            <span>
              <input
                className="search-box"
                type="search"
                value={this.state.keyword}
                onChange={this.handleChange}
                name="keyword"
                placeholder="Search artists..."
              />

              <button className="submit-btn" type="submit" value="Submit">
                Search
              </button>
            </span>
          </form>
          <br />

          {this.state.artists.map((elem) => (
            <SingerBox images={elem.images} name={elem.name} id={elem.id} />
          ))}

          <br />
        </div>
      </div>
    );
  }
}

export default Main;

您在代码中的某处硬编码了localhost 当有人搜索艺术家时,api 会访问您的本地服务器。

在此处输入图像描述

从代码中删除 localhost ,一切都应该正常工作。

暂无
暂无

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

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