簡體   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